•
•
Program Structure
Program 3
The
program
fails
in
two
ways:
1.
Take
aim
Fi
re
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
afferwards
The
program loops indefinitely.
You
can cure the
infinite looping by re-wntlng 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.
100 REMark
Western
REPeat
Zero
Case
110
LET
buLLets
= 0
120 REPeat
Bandit
130
IF
buL
Lets
=0
THEN
EXIT Bandi t
140
PRINT
"Take
aim
'l
150
PRINT
"Fire
shot"
160
LET
buLLets
=
buLLets-1
170
END
REPeat Bandi t
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
REPeaL
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
~
(opening keyword) REPeat name
(statements) (content) (statements)
END FOR name (closing keyword) END REPeal
name
In
addition the REPeal loop must normally
have
an
EXIT amongst the statements or
It
will
never end.
Note also that the EXIT statement causes control
to
go
to
the statement which
is
immediately affer the END
of
the loop
A NEXT statement may be placed
in
a
loop.
It
causes control
to
go
to
the statement •
which
is
just affer the opening keyword FOR
or
REPeal.
It
should be considered
as
a kind
of
opposite
to
the EXIT
statement.
By
a curious cOincidence the
two
words,
NEXT
and EXIT, both contain
EXT
Think
of
an
EXTenSion
to
loops and:
N means 'Now
start
again'
I means
'It's
ended'
Program 1
on
EXAMPLE 3 The situation
IS
the same
as
In
example
1.
The shenff has a gun loaded with
six
bullets
and he
IS
to
fire
at
the bandit but
two
more conditions apply:
1.
If
he hits the bandit he stops flnng and returns
to
Dodge
City.
2.
If
he
runs out
of
bullets before he
hits
the bandit, he
tells
his
partner
to
watch the
bandit while he (shenff) returns
to
Dodge City
100 REMark
Western
FOR
with
Epi Logue
110
FOR
buL
Lets
= 1
TO
6
[
120
PRINT
"Take
aim"
130 PRINT
"FIRE
A
SHOT"
140
LET
hit
=RND(9)
150
IF
hit
= 7
THEN
EXIT
buLLets
160
NEXT
buLLets
J
170
PRINT
"Watch
Bandit"
180
END
FOR
buLLets
190
PRINT
"Return
to
Dodge
Cityll
12/84
•