EasyManuals Logo

Sinclair ZX81 User Manual

Sinclair ZX81
92 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Page #36 background imageLoading...
Page #36 background image
Chapter 12 - Looping
Suppose you want to input five numbers & add them together. One way (don't type this in unless you're
feeling dutiful) is to write
10
LET
TOTAL=0
20
INPUT
A
30
LET
TOTAL=TOTAL+A
40
INPUT
A
50
LET
TOTAL=TOTAL+A
60
INPUT
A
70
LET
TOTAL=TOTAL+A
80
INPUT
A
90
LET
TOTAL=TOTAL+A
100
INPUT
A
110
LET
TOTAL=TOTAL+A
120
PRINT
TOTAL
This method is not good programming practice. It may be just about controllable for five numbers, but
you can imagine how tedious a program like this to add ten numbers would be, & a hundred would be just
impossible.
Much better is to set up a variable to count up to five & then stop the program, like this (which you
should type in):
10
LET
TOTAL=0
20
LET
COUNT=1
30
INPUT
A
40
REM
COUNT = NUMBER OF TIMES THAT A HAS BEEN INPUT SO FAR
50
LET
TOTAL=TOTAL+A
60
LET
COUNT=COUNT+1
70
IF
COUNT<=5
THEN GOTO
30
80
PRINT
TOTAL
Notice how easy it would be to change line 70 so that this program adds ten numbers, or even a
hundred.
This sort of counting is so useful that there are two special statements to make it easier: the
FOR
statement, & the
NEXT
statement. They are always used together. Using these, the program you have just
typed in does exactly the same as
10
LET
TOTAL=0
20
FOR
C=1
TO
5
30
INPUT
A
40
REM
C = NUMBER OF TIMES THAT A HAS BEEN INPUT SO FAR
50
LET
TOTAL=TOTAL+A
60
NEXT
C
80
PRINT
TOTAL
(To get this program from the previous one you just have to edit lines 20, 40, 60 & 70.
TO
is shifted 4.)
Note that we have changed COUNT to C. The counting variable - or control variable - of a
FOR
-
NEXT
loop must have a single letter for its name.
The effect of this program is that C runs through the values 1 (the initial value), 2, 3, 4 & 5 (the limit), &
for each one, lines 30, 40 & 50 are executed. Then, when C has finished its five values, line 80 is
executed.
An extra subtlety to this is that the control variable does not have to go up by 1 each time: you can
change this 1 to anything else you like by using a
STEP
part in the
FOR
statement. The most general form
for a
FOR
statement is
FOR
control variable = initial value
TO
limit
STEP
step

Other manuals for Sinclair ZX81

Questions and Answers:

Question and Answer IconNeed help?

Do you have a question about the Sinclair ZX81 and is the answer not in the manual?

Sinclair ZX81 Specifications

General IconGeneral
ProcessorZilog Z80A
Processor Speed3.25 MHz
ROM8 KB
InputMembrane keyboard
StorageCassette tape
Power Supply9V DC
Dimensions167 mm x 40 mm x 175 mm
Release Year1981
ManufacturerSinclair Research
Weight350 g
Operating SystemSinclair BASIC
RAM1 KB
PortsTV out, expansion port
DisplayTelevision (RF modulator output)

Related product manuals