Iteration
Count-controlled (FOR) loops
Count-controlled loops are written as follows:
FOR <identifier> ← <value1> TO <value2>
<statements>
NEXT <identifier>The identifier must be a variable of data type INTEGER, and the values should be expressions that evaluate to integers.
The variable is assigned each of the integer values from value1 to value2 inclusive, running the statements inside the FOR loop after each assignment. If value1 = value2 the statements will be executed once, and if value1 > value2 the statements will not be executed.
An increment can be specified as follows:
FOR <identifier> ← <value1> TO <value2> STEP <increment>
<statements>
NEXT <identifier>The increment must be an expression that evaluates to an integer. In this case the identifier will be assigned the values from value1 in successive increments of increment until it reaches value2. If it goes past value2, the loop terminates. The increment can be negative.
Example – nested FOR loops
Total ← 0
FOR Row ← 1 TO MaxRow
RowTotal ← 0
FOR Column ← 1 TO 10
RowTotal ← RowTotal + Amount[Row, Column] NEXT Column
OUTPUT "Total for Row ", Row, " is ", RowTotal
Total ← Total + RowTotal NEXT Row
OUTPUT "The grand total is ", Totalfor {variable} in {sequence}:
{statements}for i in range(1,11): #1,2,3,4,5,6,7,8,9,10
print(i, i*i)range
range(start,end,step)
range(10) => [0,1,2,3,4,5,6,7,8,9]
range(1,10) => [1,2,3,4,5,6,7,8,9]
range(1,10,2) => [1,3,5,7,9]
range(2,10,2) => [2,4,6,8]
Post-condition (REPEAT) loops
Post-condition loops are written as follows:
REPEAT
<Statements>
UNTIL <condition>The condition must be an expression that evaluates to a Boolean. The statements in the loop will be executed at least once. The condition is tested after the statements are executed and if it evaluates to TRUE the loop terminates, otherwise the statements are executed again.
Example – REPEAT UNTIL statement
REPEAT
OUTPUT "Please enter the password"
INPUT Password
UNTIL Password = "Secret"No repeat
Pre-condition (WHILE) loops
Pre-condition loops are written as follows:
WHILE <condition> DO
<statements>
ENDWHILEThe condition must be an expression that evaluates to a Boolean. The condition is tested before the statements, and the statements will only be executed if the condition evaluates to TRUE. After the statements have been executed the condition is tested again. The loop terminates when the condition evaluates to FALSE.
The statements will not be executed if, on the first test, the condition evaluates to FALSE.
Example – WHILE loop
WHILE Number > 9 DO
Number ← Number – 9
ENDWHILEwhile {condition}:
{statements}i = 1
while i <= 10:
print(i, i*i)
i += 1