FOR/NEXT

Format

FOR number1 = number2 to number3
NEXT number1

Description

These two statements are used to create a loop, so that you can execute a portion of your program a certain number of times. All of the code between the FOR and the NEXT statement will be executed a certain number of times, but at least once. The actual number of times the loop executes is dependent on number1/number2/number3. When the FOR statement is encountered in your program, number1 is assigned the value of number2. Then the statements up to the matching NEXT statement is executed one time. Then, 1 is added to number1, and number1 is compared to number3. If number1 is greater than number3 then the control passes to the statement following NEXT. Otherwise, the program loops back up to the statement following the FOR statement.

Example

FOR I = 1 TO 2
FOR J = 3 TO 5
PRINT I;
PRINT J
NEXT J
NEXT I
PRINT "AFTER THE LOOP";
PRINT I;
PRINT J;
Execution of this section of code would result in the following printout:
1 3
1 4
1 5
2 3
2 4
2 5
AFTER THE LOOP 3 6

Comments

Unlike BASICA/GWBASIC, ASIC FOR/NEXT loops execute at least 1 time. For example, the value "HELLO" will be printed in the following example. It wouldn't have been in BASICA/GWBASIC.
FOR I = 1 TO 0
    PRINT "HELLO"
NEXT I
. Unlike GWBASIC/BASICA, arrays may be used for number1 and number2. However, if number3 is an array, element zero will be used, regardless of the subscript you specify.
Loops which range from a negative to positive number are not supported (for performance reasons). Such loops will terminate after 1 iteration. For example, "FOR I =-10 to 10" will loop once.
ASIC will allow you to modify the value of number3, while GWBASIC/BASICA ignores changes.
J=1
FOR I=1 TO J
     J=2
NEXT I
The above loop will execute one time in GWBASIC/BASICA, but it will execute two times in ASIC.

Also note: The storage type of number3 must be the same as number1. For example, if "number1" is a decimal variable, then "number3" must be a decimal variable--it may not be an integer variable.