70     c+=1
 80   REPEAT UNTIL c>n
 90   PRINT "I'll count a bit
    higher"
100   n+=1
110 REPEAT UNTIL n=10
120 PRINT "OK, I'm done now"

will work fine – try it and see if you can see what is happening. You can also make a REPEAT loop continue indefinitely, if you use a zero in the REPEAT UNTIL statement. Type in this program:

10 REPEAT
20   PRINT "Hello world!"
30 REPEAT UNTIL 0

It will continue printing Hello world! to the screen, stopping only to ask if you want to scroll (unless you press the BREAK key, of course). Why? Zero can be seen in NextBASIC as false when used in this way, so the REPEAT UNTIL 0 statement will always give a false result; hence the loop will continue indefinitely. Obviously you can exit such a loop with EXIT if need be

WHILE

The WHILE command, used within a REPEAT loop, can provide an alternative way of leaving the loop before reaching the REPEAT UNTIL statement. If the condition in the WHILE statement is true, the loop continues. But if it is false, then the remaining statements in the loop will be ignored, the loop will be exited and the program will resume with the line after the REPEAT UNTIL statement. Try this:

10 REPEAT
20   INPUT "Enter a number, or
   enter a negative number to
   stop > ";n
30   WHILE n>=0
40   PRINT n
50 REPEAT UNTIL 0
60 PRINT "Thank you!"

It is a different approach to the example seen earlier, this time using WHILE to check the number entered (and also accepting any negative number to stop). WHILE can also be used to exit a loop before any statements are executed, should you need to. Try:

10 y=0
20 REPEAT : WHILE y<22
30   PRINT AT y,0;"This is
      line ";y;"."
40   y+=1
50 REPEAT UNTIL 0

You will note that when y reaches 22, the loop will exit before printing the line number. It should also be pointed out that not only can you place a WHILE anywhere within the loop, but you can also place more than one WHILE in the same loop, if you have different conditions to check to leave the loop.


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.