FOR...NEXT

The FORNEXT instruction repeats a group of statements a specified number of times.

Note: Infinite loops are possible with FOR loops. Enrichment does not check for infinite loops, so you should set time conditions appropriately.
The syntax for FORNEXT is:
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 the start-expr before the first loop iteration and is incremented by step-expr until it equals or exceeds the value of end-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 exceeds end-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:
    FOR %%Count = 1 to 10
    DO WHILE %%String != 'Car'
    %%String = READ(DD:FILE)
    IF %%String = 'Last line' THEN
     EXIT FOR
    ENDIF
    LOOP
    NEXT %%Count
    In this example, the EXIT FOR statement will leave both the DO loop and the FOR 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.