FOR

BASin

FOR

Statement/Command

FOR is always used with the keywords TO and NEXT to create a FOR-NEXT loop. This structure enables a section of the program to repeat a given number of times.

How to use FOR

FOR always forms a statement with TO. FOR is followed by a letter, an equals sign, and then two numeric values separated by TO, for example

60 FOR a=1 TO 9

The letter (a above) forms a control variable. The statements that are to be repeated follow, and one or more of these normally makes use of the control variable. The loop then ends with a NEXT statement, in which NEXT is followed by the control variable, for example

90 NEXT a

On execution, FOR deletes any variable of the same name as the control variable and assigns it an initial value equal to the value before TO (1 above). The statements are then executed with the control variable having this value. On reaching NEXT, the value of the control variable is increased by 1. If this value is less than or equal to the value after TO (the limit value 9 above), the program returns to the FOR statement and the FOR-NEXT loop is repeated. If the control variable has a greater value than the limit value, then the loop ends and the program continues with the statement after NEXT.

In the above example, the loop is repeated nine times with the control variable a increasing from 1 to 9. On leaving the loop, a has a value of 10.

Note that the BASIC does not distinguish between capital and lower-case letters when naming the control variable.

Using STEP in a FOR-NEXT loop

STEP is a keyword that can be incorporated in a FOR statement if the control variable is to increase by a value other than 1 or decrease. STEP follows the limit value and is followed by a numeric value, for example

60 FOR a=1 TO 9 STEP 2

The control value is increased by the step value (2 above) until it is greater than the limit value. The control variable a has successive values of 1, 3, 5, 7 and 9 and leaves the loop with a value of 11.

A negative step value causes the control variable to decrease. In this case, the initial value must be greater than the limit value and the loop ends when the value of the control variable is less than the limit value, for example

60 FOR a=9 TO 1 STEP -1

The value of a decreases from 9 to 1 and leaves the loop with a value of 0.

Nesting loops

One or more FOR-NEXT loops may be placed inside each other, a procedure called "nesting" loops. The order of the control variables in the NEXT statements must be the reverse of the of the order of the control variables in the FOR statements. FOR-NEXT loops may be nested to any depth, that is as many loops as required may be placed inside each other.

Format

  • FOR letter=num-expr TO num-expr [STEP num-expr]
  • NEXT letter

See also

Chapter 4.