The for Statement
They can be combined in one list, executed left to right:
12.1 Three kinds of for-list element
They can be combined in one list, executed left to right:
'for' i := 1 'step' 1 'until' n 'do' S; 'comment' arithmetic progression;
'for' x := x * 2 'while' x < 1000 'do' S; 'comment' while element;
'for' k := 2, 3, 5, 7, 11 'do' S; 'comment' list of values;'for' i := 1, 2, 4 'step' 4 'until' 20, 100, i + 1 'while' i < 105 'do'
outinteger(1, i);
'comment' 1 2 4 8 12 16 20 100 101 102 103 104;12.2 Semantics of step-until
The Report defines for V := A step B until C do S as roughly:
Important consequences:
B and C are re-evaluated on every iteration (they behave like call-by-name expressions). If the loop body changes them, the loop changes.
A negative step counts down: for i := 10 step -1 until 1 do.
If the initial value already exceeds the limit, the body is not executed.
After normal exhaustion of the for list, the value of the controlled variable is undefined (Revised Report). After exit by goto, it keeps its current value.
V := A;
L1: if (V - C) × sign(B) > 0 then goto element exhausted;
S;
V := V + B;
goto L1;12.3 while elements
for V := E while B do S means: assign V := E, test B, execute S, then repeat by re-evaluating E — the assignment happens before every test:
To write a plain "while" loop where no variable needs updating, a dummy variable or a goto loop is used:
'begin'
'real' x;
'for' x := 1, x * 2 'while' x <= 100 'do'
outreal(1, x); 'comment' 1 2 4 8 16 32 64;
'end''for' dummy := 0 'while' n > 1 'do'
n := 'if' n - 2 * (n % 2) = 0 'then' n % 2 'else' 3 * n + 1;12.4 Nested loops: multiplication table
'begin'
'integer' i, j;
'for' i := 1 'step' 1 'until' 9 'do'
'begin'
'for' j := 1 'step' 1 'until' 9 'do'
outinteger(1, i * j);
outstring(1, "\n")
'end'
'end'12.5 Jumping into a for statement
A goto from outside into the body of a for statement is undefined (the Report says the effect is undefined); jumping *out* is fine.
12.6 for in other ALGOLs
for i:= 1(1)n for i:= 1 step 1 until n do for i:= 1 until n do (step defaults to 1; limit evaluated once)
FOR i FROM 1 BY 1 TO n WHILE cond DO... OD (all parts optional; bounds evaluated once) for i:= 1 to n do / downto