FOR

The FOR instruction executes a statement block a specified number of times.

Syntax

FOR counter = start TO finish [ STEP value ]
   { statement
   | EXIT FOR
   | CONTINUE FOR }
   [...] 
END FOR
  1. counter is the loop counter and must be an integer variable.
  2. start is an integer expression used to set an initial counter value.
  3. finish is any valid integer expression used to specify an upper limit for counter.
  4. value is any valid integer expression whose value is added to counter after each iteration of the statement block.
  5. When the STEP keyword is not given, counter increments by 1.
  6. statement is any instruction supported by the language.
  7. If value is less than 0, counter is decreased. In this case, start should be higher than finish.

Usage

The FOR instruction block executes the statements up to the END FOR keyword a specified number of times, or until EXIT FOR terminates the FOR statement. The CONTINUE FOR instruction skips the next statements and continues with the next iteration.

On the first iteration through the loop, the counter is set to the initial expression at the left of the TO keyword. For all further iterations, the value of the increment expression in the STEP clause specification (1 by default) is added to the counter in each pass through the block of statements. When the sign of the difference between the values of counter and the finish expression at the right of the TO keyword changes, the runtime system exits from the FOR loop.

The FOR loop terminates after the iteration for which the left- and right-hand expressions are equal. Execution resumes at the statement following the END FOR keywords. If either expression returns NULL, the loop cannot terminate, because the boolean expression "left = right" cannot become TRUE.

A value that equals 0 causes an unending loop unless there is an adequate EXIT FOR statement.

Using NULL for start, finish or value is treated as 0. There is no way to catch this as an error.

If statement modifies the value of counter, you might get unexpected results at runtime. In this case, it is recommended that you use a WHILE loop instead.

It is highly recommended that you ensure that statement does not modify the values of start, finish or value.

MAIN
  DEFINE i, i_min, i_max INTEGER
  LET i_min = 1
  LET i_max = 10
  DISPLAY "Count from " || i_min || " to " || i_max 
  DISPLAY "Counting forwards..."
  FOR i = i_min TO i_max 
      DISPLAY i 
  END FOR
  DISPLAY "... and backwards."
  FOR i = i_max TO i_min STEP -1
      DISPLAY i
  END FOR
END MAIN