FOR loop

There are two forms of the FOR loop:

FOR variable := expression1 TO expression2
    { statements; }
END;
|
FOR variable := expression1 FOR expression2
    { statements; }
END;

At the beginning of the loop, the counter variable, variable, is assigned the value of expression1 and then, each time around the loop, the value is incremented and compared to the final expression. In the first form, the final expression is expression2, whereas in the second form, the final expression is expression1 + expression2 - 1. All the statements are executed each time around the loop.

The final expression is calculated once at the start of the loop and not re-evaluated again.

The loop counter variable, variable, must be an integer.

The FOR loop can be terminated early by using the BREAK statement. This causes execution to move to the statement after the END of the current loop.

Example

These two loops are identical:

FOR i := 0 TO 9
  PRINT(i, "\n");
END;

// OR...

FOR i := 0 FOR 10
  PRINT(i, "\n");
END;

Note: the value of expression2 is calculated once at the start of the loop and not recalculated again, i.e. the following loop will still run 10 times even though the value of j is being modified inside the loop:

INT i;
INT j := 10;

FOR i := 1 TO j
  PRINT(i, "\n");
  j := j - 1;
END;

This loop terminates either when the user presses the space bar or the function returns a non-zero value.

DO
  b := Func();
  IF b != 0 THEN BREAK; END;
  key := GETKEY();
WHILE key != ' '
END;

Similarly, this loop terminates either when the user presses the space bar or the function returns a non-zero value.

DO
  b := Func();
  IF b != 0 THEN BREAK; END;
  key := GETKEY();
UNTIL key = ' '
END;

This loop either repeats 10 times or terminates when the user presses the space bar.

FOR i := 0 FOR 10
  key := GETKEY();
  IF key = ' ' THEN BREAK; END;
END;