Home > CBM > BASIC > Keywords > For | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
FOR variable = initial TO final [ STEP delta ] [ : statement ] ... [ statement : ] ... NEXT [ variable [ , variable ] ... ]
Program flow control. Execute statement(s) one or more times, and maintain a running counter.
The entire FOR...NEXT construct may be on a single line, or span multiple lines (not only 2 lines like Syntax shows). The statement(s) will be executed at least once in Commodore BASIC. (In some other versions, the statement(s) may be skipped entirely, depending on the parameters.) FOR begins by setting the named variable to the initial value. Then all the statements (if any) are executed. When NEXT is reached, the value of variable is updated by adding delta to the variable. Finally a test is made, based on delta and final:
The initial, final, and delta values may be specified with variables of any numeric type. If so, those variables will not be referenced again by FOR/NEXT. This means during execution of the statement(s), any changes to those variables will have no effect on the loop. However changing the variable will affect the loop. Although BASIC will convert initial, final, and/or delta into floating-point format if they are integers, the variable must be floating-point type; SYNTAX ERROR will result otherwise. BASIC assigns the initial value to variable before it processes the final and delta parameters. This means final and delta should not reference the old value of variable. For example, the following will not step from 1 to 8:
If the results puzzle you, know that BASIC is stepping from 1 to 1. This is because the "TO K" refers to the new value of K set by "FOR K = 1". Besides the main use of executing a set of statements multiple times, it is often used with no statements between FOR/NEXT to slow execution. This use is not portable because the timing delay is machine-dependant. However the delay is usually for the benefit of a human user and not for time-critical code, so porting such code will not cause the program to crash (althoug it may run too fast or slow for the comfort of the user). FOR/NEXT is typically used when the number of loops is known in advance or can be easily calculated. If this is not the case, other techniques are often used: typically IF/THEN/GOTO or DO/LOOP. Example:
© H2Obsession, 2014 |