ZX 81 - BASIC Programming

Sinclair ZX Spectrum
Chapter 12.2 - Looping

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

(Actually we have cheated slightly here: it should really be GOTO 21 instead of GOTO 30. This will have the same effect in our program.)

3. Run the program, & then type

PRINT C

Why is the answer 6, & not 5?

[Answer: the NEXT statement in line 60 is executed 5 times, and each time 1 is added to C.] What happens if you put STEP 2 in line 20?

4. Change the third program so that instead of automatically adding five numbers, it asks you to input how many numbers you want adding. When you run this program, what happens if you input 0, meaning that you want no numbers adding? Why might you expect this to cause problems to the computer, even though it is clear what you mean? (The computer has to make a search for the statement NEXT C, which is not usually necessary.) In fact this has all been taken care of.

5. Try this program, to print out the numbers from 1 to 10 in reverse order.

10 FOR N=10 TO 1 STEP -1

20 PRINT N

30 NEXT N

Convert this into a program that does not use FOR-NEXT loops in the same way that you would convert program 3 into program 2 (see exercise 2). Why does the negative step make is slightly different?

Sinclair ZX Spectrum

  Previous Page Back Next Page