The FOR . . . NEXT looping construct provides a way to execute code a specific amount of times. See the section below on the proper way to exit a loop before the counter variable reaches the limit. A starting and ending value are specified:

for var = 1 to 10

{BASIC code}

next var

In this case, the {BASIC code} is executed 10 times, with var being 1 the first time, 2 the second, and on through 10 the tenth time. Optionally (and usually) var is used in some calculation(s) in the {BASIC code}. For example if the {BASIC code} is print var ^ 2, then a list of squares for varwill be displayed upon execution.

The specified range could just as easily be 2 TO 20, instead of 1 TO 10, but since the loop always counts +1 at a time, the first number must be less than the second. The way around this limitation is to place STEP n at the end of for FOR statement:

for index = 20 to 2 step -1

{BASIC code}

next index

This loops 19 times returning values for index that start with 20 and end with 2. STEP can be used with both positive and and negative numbers and it is not limited to integer values. For example:

for x = 0 to 1 step .01

print "The sine of "; x; " is "; sin(x)

next x

Optional variable with "next"

Liberty BASIC 3 makes the use of a variable after "next" optional, but if one is designated, it must match the variable use with "for". Example:

Correct:

for x = 0 to 1 step .01

print "The sine of "; x; " is "; sin(x)

next

Incorrect:

for x = 0 to 1 step .01

print "The sine of "; x; " is "; sin(x)

next y

Exiting a loop prematurely

GOSUB, FUNCTION and SUB may be used within a FOR/NEXT loop because they only temporarily redirect program flow or call on other parts of the program. Program execution resumes within the FOR/NEXT loop in these instances. Program execution does not return to the FOR/NEXT loop if GOTO is used within the loop. GOTO should not be used to exit a FOR/NEXTloop. "EXIT FOR" will correctly exit the loop before it would have terminated normally.

for index = 1 to 10

print "Enter Customer # "; index

input customer$

if customer$ = "" then [quitEntry] 1

'don't cut out of a for/next loop like this

cust$(index) = customer$

next index

[quitEntry]

. . . is not allowed! Rather use while ... wend:

index = 1

while customer$ <> "" and index <= 10

print "Enter Customer # "; index

input customer$

cust$(index) = customer$

index = index + 1

wend

EXIT FOR

If it is necessary to exit a loop before the counter variable has reached its final value, use the EXIT FOR statement. This allows the program to exit the loop properly and to preserve the current value of the counter variable. Use it like this: