Syntax

Repeats a block while a counter goes from a start value to an end value, adding the step after each pass.

FOR <var> = <start> TO <end> [STEP <step>]
  <statements>
NEXT [<var>]

Also written : TO, STEP, NEXT

Parts

<var>The counter, an ordinary numeric variable (a sigil such as # is allowed). After NEXT, the name is optional; when given, it must be this counter.
<start>The first value of the counter.
<end>The last value the counter may take. Read once, before the first pass.
<step>What is added to the counter after each pass. Default 1. Negative counts down, decimals are allowed, 0 stops the program. Read once, before the first pass.
<statements>The body of the loop.

Good to know

  • The sign of the step picks the direction. A positive step runs while the counter is <= end; a negative step while it is >= end. FOR i = 5 TO 1 runs zero times.
  • STEP 0 stops the program with the error "BASIC FOR STEP cannot be zero". It is not an endless loop.
  • After the loop, the counter keeps its last value: end + step when the loop ran to the end, its value at the EXIT when it was left early, the start value when it never ran.
  • Changing a variable used in <end> or <step> inside the loop changes nothing. Changing the counter itself does: the next pass adds the step to the new value.
  • NEXT j that does not name the counter of the innermost FOR is a compile error: "NEXT variable j does not match FOR variable i".
  • A string containing TO or STEP in the FOR line breaks it: FOR i = Len("A TO B") TO 8 compiles, but the program does not start. Compute the value into a variable before the loop.
  • Known flaw: when the counter is read after NEXT, a FUNCTION that calls itself from inside that loop can cut the outer loop short. Copy the value you need inside the loop instead.

Example

total = 0FOR i = 1 TO 5  total = total + iNEXT iConsole(Str(total))   ' 15Console(Str(i))       ' 6FOR n = 10 TO 1 STEP -3  Console(Str(n))     ' 10, 7, 4, 1NEXT
In the manual : Control flow