Sinclair QL Beginner's Manual page 97

Hide thumbs Also See for QL:
Table of Contents

Advertisement

Suppose that someone has secretly taken all the bullets out of the sheriff's gun. What happens if you
simply change the 6 to 0 in each program?
Program 1
100 REMark Western FOR Zero Case
110 FOR bullets = 1 to 0
120
PRINT"Take aim"
130
PRINT "Fire a shot"
140 END FOR bullets
This works correctly. There is no output. The 'zero case' behaves properly in SuperBASIC
Program 2
100 REMark Western REPeat Fails
110 LET bullets = 0
120 REPeat bandit
130
PRINT "Take aim"
140
PRINT "Fire shot"
150
LET bullets = bullets - 1
160
IF bullets = 0 THEN EXIT bandit
170 END REPeat bandit
The program fails in two ways:
1. Take aim
Fire a shot
Is printed though there were never any bullets
2. By the time the variable, bullets, is tested in line 160 it has the value -1 and it never becomes zero
afterwards. The program loops indefinitely. You can cure the infinite looping by re-writing line 160:
160 IF bullets < 1 THEN EXIT bandit
There is an inherent fault in the programming which does not allow for the possible zero case. This
can be corrected by placing the conditional EXIT before the print statements.
Program 3
100 REMark Western REPeat Zero Case
110 LET bullets = 0
120 REPeat Bandit
130
IF bullets = 0 THEN EXIT Bandit
140
PRINT "Take aim"
150
PRINT "Fire shot"
160
LET bullets = bullets - 1
170 END REPeat Bandit
This program now works properly whatever the initial value of bullets as long as it is a positive whole
number or zero. Method 2 corresponds to the REPEAT.. UNTIL loop of some languages. Method 3
corresponds to the WHILE....ENDWHILE loop of some languages. However the REPeat.....END
REPeat with EXIT is more flexible than either or the combination of both.
If you have used other BASICs you may wonder what has happened to the NEXT statement. We will
re-introduce it soon but you will see that both loops have a similar structure and both are named.
FOR name =
(statements)
END FOR name
(opening keyword)
(content)
(closing keyword)
REPeat name
(statements)
END REPeat name

Advertisement

Table of Contents
loading

Table of Contents