登录

Iteration (repetition)

Count-controlled (FOR) loops

Count-controlled loops are written as follows:

FOR <identifier> ← <value1> TO <value2>
    <statement(s)>
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.

It is good practice to repeat the identifier after NEXT, particularly with nested FOR loops. An increment can be specified as follows:

FOR <identifier> ← <value1> TO <value2> STEP <increment>
    <statement(s)>
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 ", Total

for {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
    <statement(s)>
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 loop
REPEAT
    OUTPUT "Please enter the password"
    INPUT Password
UNTIL Password = "Secret"

Pre-condition (WHILE) loops

Pre-condition loops are written as follows:

WHILE <condition>
    <statement(s)>
ENDWHILE

The 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
    Number ← Number – 9
ENDWHILE

while {condition}:
	{statements}
i = 1
while i <= 10:
	print(i, i*i)
	i += 1

登录