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
%%counteris a variable name that will contain the counter value during each loop execution. The%%countervariable is set to thestart-exprbefore the first loop iteration and is incremented bystep-expruntil it equals or exceeds the value ofend-expr.start-expris the initial numeric value to set the%%countervariable prior to the first loop iteration. It may be a simple number or a complex expression.end-expris the numeric value that%%countermust equal or exceed to terminate the loop execution. It may be a simple number or a complex expression.step-expris the numeric value to increment%%counterat 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-exprare optional. The default STEP is 1. - If
start-exprexceedsend-exprat 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 %%CountEXIT FORstatement will leave both theDOloop and theFORloop. 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
NEXTstatement 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.
-