FOR...NEXT
The FOR…NEXT instruction repeats a group of statements a specified number of times.
FOR %%counter = start-expr TO end-expr [STEP step-expr]
Statements
[EXIT]
[EXIT FOR]
[ITERATE]
[ITERATE FOR]
statements
NEXT [%%counter]
where
%%counter
is a variable name that will contain the counter value during each loop execution. The%%counter
variable is set to thestart-expr
before the first loop iteration and is incremented bystep-expr
until it equals or exceeds the value ofend-expr
.start-expr
is the initial numeric value to set the%%counter
variable prior to the first loop iteration. It may be a simple number or a complex expression.end-expr
is the numeric value that%%counter
must equal or exceed to terminate the loop execution. It may be a simple number or a complex expression.step-expr
is the numeric value to increment%%counter
at the end of each loop iteration. It may be a simple number or a complex expression. In addition, it may be either positive or negative.
Hints
- The STEP keyword and
step-expr
are optional. The default STEP is 1. - If
start-expr
exceedsend-expr
at the start of the first loop iteration, the loop will not be executed. - EXIT and EXIT FOR both immediately leave a given loop. EXIT by itself leaves the innermost FOR or DO loop. Since EXIT can also leave a DO loop, EXIT FOR is more explicit. For example:
In this example, theFOR %%Count = 1 to 10 DO WHILE %%String != 'Car' %%String = READ(DD:FILE) IF %%String = 'Last line' THEN EXIT FOR ENDIF LOOP NEXT %%Count
EXIT FOR
statement will leave both theDO
loop and theFOR
loop. An EXIT alone would have only left the inner DO loop.-
ITERATE or ITERATE FOR will cause the next iteration of the loop. The %%counter variable is incremented, and the next loop iteration begins at the top. Any statements below ITERATE are not executed until the iterations are complete.
-
The use of the %%counter variable in the
NEXT
statement is optional. Using a variable can help you reference which loop is ending, especially when you have nested FOR loops. -
If you omit the FOR on the EXIT FOR statement, the EXIT means to exit the innermost loop. If you nest a DO inside a FOR, you can have an EXIT FOR statement that will exit the outer FOR loop.
-
You can use an ITERATE FOR substatement to cause the next iteration of the FOR loop to begin executing immediately. If you specify ITERATE by itself, it goes to the top of the innermost loop.
-