FOR

Syntax

FOR <varname> [AS <type>] = <start_value> TO <end_value> [STEP <step_value>]
  <statements>
NEXT [<varname>]

The FOR … NEXT loop initializes a counter variable and executes the statements until the counter variable equals the value in the TO clause. After each iteration, the counter variable is incremented by the step value or 1 in case the step value was not specified. For example:

DIM i AS BYTE
FOR i = 1 TO 30 STEP 3
  PRINT i
NEXT i

As you can see above, the counter variable must be pre-defined. If the variable is not pre-defined, you can use the AS keyword to specify the type and this way the compiler will automatically define the variable before starting the loop. The following code is identical to the one above:

FOR i AS BYTE = 1 TO 30 STEP 3
  PRINT i
NEXT i

Warning

The counter variable, the start value, the end value and the step value must all be of the same numeric type and this type is concluded from the counter variable. All the other expresions will be converted to this type if possible, otherwise a compile-time error will be thrown.

Note

The variable name can be omitted in the NEXT statement.

You can use the CONTINUE FOR command to skip the rest of the statements in the FOR … NEXT block and go to the next iteration, for example:

REM -- print numbers from 1 to 10, except 5 and 7
FOR num AS BYTE = 1 TO 10
  IF num = 5 OR num = 7 THEN CONTINUE FOR
  PRINT num
NEXT

Finally, you can use the EXIT FOR statement to early exit a FOR … NEXT loop.

DIM a$ AS STRING * 1
FOR i AS BYTE = 1 TO 10
  PRINT "iteration #"; i : INPUT "do you want to continue? (y/n)"; a$
  IF a$ = "n" THEN EXIT FOR
  PRINT i
NEXT i