Error trapping within REPEAT … REPEAT UNTIL loops as well as within subroutines and procedures is localised. Refer to the last section of Chapter 4 – Localised Error Trapping for a complete example that covers all cases of error trapping in these programming structures.
A control variable has not just a name and a value, like an ordinary variable, but also a limit, a step, and a reference to the statement after the corresponding FOR statement. Persuade yourself that when the FOR statement is executed all this information is available (using the initial value as the first value the variable takes), and also that this information is enough for the NEXT statement to know by how much to increase the value, whether to jump back, and if so where to jump back to. Run the third program above and then type:
PRINT count
Why is the answer 6, and not 5? (Answer: the NEXT command in line 60 is executed five times, and each time 1 is added to count. The last time, count becomes 6; and then the NEXT command decides not to loop back, but to carry on, count being past its limit.)
What happens if you put STEP 2 in line 20?
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 for the computer, even though it is clear what you mean? (The computer has to make a search for the command NEXT count, which is not usually necessary.) In fact this has all been taken care of.
In line 10 of the fourth program above, change 10 to 100 and run the program. It will print the numbers from 100 to 79 on the screen, and then say scroll? at the bottom. This is to give you a chance to see the numbers that are about to be scrolled off the top. If you press n, BREAK or the space bar, the program will stop with the report D BREAK - CONT repeats. If you press any other key, then it will print another 22 lines and ask you again.
Delete line 30 from the fourth program. When you run the new curtailed program, it will print the first number and stop with the message 0 OK. If you type:
NEXT n
The program will go once round the loop, printing out the next number.
Refer back to the example in the REPEAT UNTIL section, where the message x is 1, but it isn't 1 was displayed incorrectly. Rewrite this using WHILE so that the message does not appear when x is indeed 1. Change the value of x in line 10 to check this works correctly.
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.