Sinclair ZX81 User Manual page 37

Hide thumbs Also See for ZX81:
Table of Contents

Advertisement

where the control variable is a single letter, & the initial value, limit & step are all numeric expressions. So,
if you replace line 20 in the program by
20 FOR C=1 TO 5 STEP 3/2
then C will run through the values 1, 2.5 & 4. Notice that you don't have to restrict yourself to whole
numbers, & also that the control value does not have to hit the limit exactly - it carries on looping as long as
it is less than or equal to the limit (but see exercise 4).
You must be careful if you are running two FOR - NEXT loops together, one inside the other. Try this
program, which prints out a complete set of 6-spot dominoes.
10 FOR M=0 TO 6
20 FOR N=0 TO M
30 PRINT M;":";N;" ";
40 NEXT N
50 PRINT
60 NEXT M
You can see that the N-loop is entirely inside the M-loop - they are properly nested. What must be
avoided is two FOR-NEXT loops that overlap without either being entirely inside the other, like this:
10 FOR M=0 TO 6
20 FOR N=0 TO M
30 PRINT M;":";N;" ";
WRONG
40 NEXT M
50 PRINT
60 NEXT N
The FOR-NEXT loops must either be one inside the other, or be completely separate.
Another thing to avoid is jumping into the middle of a FOR-NEXT loop from the outside. The control
variable is only set up properly when its FOR statement is executed, & if you miss this out the NEXT
statement will confuse the computer. You might get error report 1 or 2 (meaning that a NEXT statement
does not contain a recognised control variable) if you're lucky.
Summary
Statements: FOR , NEXT , TO , STEP
Exercises
1. Rewrite the program in chapter 11 that prints out the character set, using a FOR-NEXT loop (Answer in
chapter 13.)
2. A control variable has not just a name & a value, like an ordinary variable, but also a limit, a step, & a
line number for looping back to (the line after the FOR statement where it was set up). Persuade yourself
first, that when the FOR statement is executed all this information is available (using the initial value as the
first value it takes), & second, that (using as an example our second & third programs), this information is
enough to
convert the one line.
NEXT C
into the two lines
LET C=C+1
IF C<=5 THEN GOTO 30
M-loop
N-loop
|
|
|
N-loop
|
|
M-loop
M-loop
N-loop
|
|
|
|
M-loop
|
N-loop

Hide quick links:

Advertisement

Table of Contents
loading

Table of Contents