Chapter 3 – Looping

Using FOR, TO and NEXT

Suppose you want to input five numbers and add them together. One way (don't type this in unless you are feeling dutiful) is to write:

 10 total=0
 20 INPUT a
 30 total+=a
 40 INPUT a
 50 total+=a
 60 INPUT a
 70 total+=a
 80 INPUT a
 90 total+=a
100 INPUT a
110 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, and to add a hundred would be just impossible.

Much better is to set up a variable to count up to 5 and then stop the program, like this (which you should type in):

10 total,count=0,1
20 INPUT a
30 REM count=number of times
   that a has been input so
   far
40 total += a
50 count += 1
60 IF count <= 5 THEN GO TO 20
70 PRINT total

Notice how easy it would be to change line 60 so that this program adds ten numbers, or even a hundred.

This sort of counting is so useful that there are two special keywords to make it easier: FOR and NEXT that are always used together. Using these, the program you have just typed in does exactly the same as:

10 total = 0
20 FOR count = 1 TO 5
30   INPUT a
40   ;count=number of times
   that a has been input so
   far
50   total += a
60 NEXT count

ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.