English
Language : 

NSB8 Datasheet, PDF (102/158 Pages) List of Unclassifed Manufacturers – BASIC interpreter for Z80 family
THE FOR NEXT LOOP
grifo®
ITALIAN TECHNOLOGY
BODY OF THE LOOP
BASIC includes facilities for the FOR NEXT loop (namely the statements FOR and NEXT) in order
to provide for repetition of any arbitrary block of BASIC statements. The block to be repeated (also
called the BODY of the loop), symbolized here as {BODY}, is sandwiched between a FOR statement
and a NEXT statement.
Example #1
10 FOR I=1 TO 10
{BODY}
99 NEXT
100 REM More program statements.
In example #1, the statements represented by {BODY} will be repeated 10 times unless specific
action is taken within the body to terminate repetition prior to the completion of the 10th cycle (for
example, see the sections on EXIT).
THE CONTROL VARIABLE AND THE LIMIT VALUE
In line 10, I, a numeric variable, is called the control variable of the loop. By using I as a counter,
BASIC will be able to know when to quit repeating {BODY}. In the example, the first time {BODY}
is executed, I will be set to 1 (the initial value, as specified in the FOR statement). After that,
whenever execution proceeds through {BODY} and reaches the NEXT statement in line 99, I will
be increased by 1. At such times, BASIC will compare I against 10 (the limit value set in line 10). If
I is less than or equal to the limit value, execution returns once more to the start of {BODY}, and the
cycle begins again. On the other hand, if I is greater than the limit value, then repetition ceases, and
execution continues beyond the NEXT statement (in the case of example #1, at line 100).
THE OPTIONAL STEP VALUE
In the example #1, I was increased by 1 after every repetition of the body. It is often useful for the
value of the control variable to be increased by a different amount than 1 each time, or perhaps it
should even be decreased! This is accomplished by adding a STEP clause to the FOR statement.
Example #2
10 FOR J=1 TO 10 STEP 2
{BODY}
99 NEXT
Example #3
10 FOR K(3)=5 TO 1 STEP -1
{BODY}
99 NEXT
Page 90
NSB8
Rel. 5.10