The ZX80 Operating Manual

Sinclair ZX Spectrum
Very often we come up against problems which involve repeated operations. The square rooting program in chapter 8 was one example of such a problem, and the program was written so that the computer jumped back to line 50, if the test conditions in statements 70 or 80 were not met, and tried again and again until the conditions were met.

Programs of this sort are called iterative. By using iterative techniques it's possible to get the computer to do a lot of work with a very short program.

It's easy to make a program iterative all you have to do is to put a GO TO statement at the end of the program to jump the computer back to the first statement (or any other suitable statement). One snag is that such iterative programs can get stuck in endless loops.

One way to avoid this is to allow the computer to go round only a set number of times. One way of doing this would be to use IF and GO TO statements.

Consider the following program which prints $ 152 times.

10 LET J=1
20 PRINT "$"
30 IF J = 152 THEN GO TO 60
40 LET J = J + 1
50 GO TO 20

First the program sets J (the loop control variable) to 1. Then it prints $. Then it tests to see if J = 152. It isn't and so the computer goes on to line 40 which increments the value of J by 1 to 2. The computer passes on to 50 which tells it to jump back to 20. This process goes on until J = 152 when the IF statement is satisfied and the computer jumps out of the loop to line 60.

The arrows on the program help you to see where the program is going; for short programs this is quicker than drawing a flow diagram and does make it easier to see what the program is doing.

The program took 5 lines (if you don't count the STOP statement, which doesn't actually do anything it just serves as a target for the GOTO in line 30.

Loops are so useful that you'd have thought that there was an easier way of writing programs using them. Well there is. Turn to chapter 10.

Sinclair ZX Spectrum

  Previous Page Back Next Page