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