FOR / NEXT

Top  Previous  Next

 

The FOR / NEXT statement defines a group of statements to be executed with an iterative control variable.

 

 

Format

 

FOR var = start.expr TO limit.expr {STEP step.expr}

statement(s)

NEXT {var}

 

where

 

varis the loop control variable.

 

start.exprevaluates to the value to be placed in var for the first iteration of the loop.

 

limit.exprevaluates to the value beyond which var must not pass.

 

step.exprevaluates to the value by which var should be incremented between iterations of the loop. If omitted, step.expr defaults to one.

 

statement(s)are statement(s) to be executed within the loop.

 

 

The FOR / NEXT statement executes statement(s) for values of var from start.expr to limit.expr in increments of step.expr. If step.expr is positive, the loop continues while the value of var is less than or equal to limit.expr. If step.expr is negative, the loop continues while the value of var is greater than or equal to limit.expr. The value of var on leaving the loop is the last value for which the loop was executed or start.expr if the initial value was already out of range.

 

The value of var should not be changed within the loop as this may lead to unexpected results.

 

Use of non-integer values for start.expr, limit.expr and step.expr is not recommended where rounding errors in incrementing var and the loop termination comparison may lead to unexpected effects.

 

For best performance, limit.expr and step.expr should be constants or simple variable references as they are evaluated for every iteration of the loop.

 

If  var is present in the NEXT statement it must be the same var as in the FOR statement at the head of the loop. Use of var in the NEXT statement aids program readability and is checked by the compiler for correct matching of FOR and NEXT statements.

 

The WHILE, UNTIL and EXIT statements can be used with the FOR / NEXT loop to provide another loop termination control. The CONTINUE statement causes a jump to the start of the next iteration.

 

FOR / NEXT loops may be nested to any depth.

 

The FOR.STORE.BEFORE.TEST option of the $MODE compiler directive can be used to modify the behaviour of FOR/NEXT constructs to store the new value of the control variable before testing for the end condition.

 

 

Examples

 

FOR I = 1 TO 10 STEP 2

  DISPLAY I

NEXT I

 

This program fragment displays the values 1, 3, 5, 7 and 9. The final value of I on leaving the loop is 9.

 

 

FOR I = 1 TO 20

UNTIL A(I) < 0

  DISPLAY A(I)

NEXT I

 

This program fragment displays elements of matrix A. The loop terminates if an element is found with a negative value.

 

 

See also:

CONTINUE, EXIT, LOOP/REPEAT, WHILE, UNITL