FOR
The FOR instruction executes a statement block a specified number
of times.
Syntax
FOR counter = start TO finish [ STEP increment ]
{ statement
| EXIT FOR
| CONTINUE FOR }
[...]
END FOR
- counter is a variable defined as
TINYINT,SMALLINT,INTEGERorBIGINT. - start is an expression used to set an initial counter value.
- finish is any valid expression used to specify an upper limit for counter.
- increment is any valid expression whose value is added to counter after each iteration of the statement block.
- When the
STEPkeyword is not given, counter increments by 1. - statement is any instruction supported by the language.
- If increment 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.
An increment that equals 0 causes an unending loop unless there is an adequate
EXIT FOR statement.
Using NULL for start, finish or
increment is treated as 0. There is no way to catch this as an error. It is not
recommended to use NULL as FOR loop values.
The body of the FOR loop must not modify the values of start,
finish or increment. When the body of the FOR
loop modifies the value of counter, the behavior of the loop is undefined.
Consider using a WHILE loop
instead.
Example
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