FOR, NEXT

The FOR and NEXT keywords define a program block which is executed a specific number of times in a loop.

Syntax:

FOR variable, start_value, stop_value, increment commands...
NEXT

Discussion:

The keyword FOR marks the beginning of a group of commands to be executed a multiple number of times. FOR requires a variable to be specified which acts as a counter (it need not be an integer), a starting value for the counter, a stop value, and an increment. The NEXT keyword marks the end of the group of commands. FOR- NEXT loops may be nested. The number of FOR and NEXT commands must be the same.

Upon reaching a FOR command, the expressions for the start, stop, and increment values are evaluated and saved. The stop and increment values are not evaluated again, even if the expressions defining the values consist of variables whose values change within the program block. Only the values valid at the beginning of the FOR loop are used.

If the start value and stop value are the same, the loop executes exactly once.

If the start value is less than the stop value, then the loop continues until the counter variable is greater than the stop value.

If the start value is greater than stop value, then the loop continues until the counter variable is less than the stop value.

Note that only integral values can be reliably represented exactly using computer floating point math, so comparing two floating point values for equality is not advised. Rather than using floating point ranges in loops, it is advised that the loop is conducted over an integer range and then converted from the index to the actual value of interest. More information on the accuracy of floating point arithmetic can be found in this helpful Wikipedia article: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems

Example:

FOR a, 0.2, 2, 0.2
   PRINT a
NEXT
 
j = 5
k = 0
 
FOR i, j, j + 5, 2
   k = i + j + k
NEXT

Next: