This statement executes all the commands enclosed between
the FOR and NEXT statements repetitively, according to the start
and end values. The start value and the end value are the
beginning and ending counts for the loop variable. The loop
variable is added to or subtracted from during the FOR/NEXT
loop.
The logic of the FOR/NEXT statement is as follows. First, the loop
variable is set to the start value. When the program reaches a
program line containing the NEXT statement, it adds the STEP
increment (default = 1) to the value of the loop variable and
checks to see if it is higher than the end value of the loop. If the
loop variable is less than or equal to the end value, the loop is
executed again, starting with the statement immediately following
the FOR statement. If the loop variable is greater than the end
value, the loop terminates and the program resumes immediately
following the NEXT statement. The opposite is true if the step size
is negative.
EXAMPLE A: EXAMPLE B:
10 FOR L = 1 TO 10 10 FOR L=10TO 1 STEP -1
20 PRINT L 20 PRINT L
30 NEXT L 30 NEXT L
40 PRINT “I’M DONE! L = ”;L 40 PRINT “I’M DONE! L = ”;L
Program A prints the numbers from one to 10 followed by the
message I’M DONE! L = 11. Program B prints the numbers down
to one and then I'M DONE! L = 0
The end value of the loop may be followed by the word STEP and
another number or variable, ln this case, the value following the
STEP is added each time instead of one. This allows counting
backwards, by fractions, or in increments other than one.
The user can set up loops inside one another. These are known
as nested loops. Care must be taken when nesting loops so the
last loop to start is the first one to end.
EXAMPLE:
10 FOR L = 1 TO 100
20 FOR A = 5 TO 11 STEP .5
30 NEXT A
40 NEXT L
17-32