Chapter 10 - If...
All the program we've seen so far have been pretty predictable - they went straight through doing all the
instructions, & then maybe went back to the beginning again. This is not all that useful. In practice the
computer would be expected to make decisions & act accordingly; it does this using the
IF
statement.
Clear the computer (using
NEW
), & type in & run this terribly amusing little program:
10
PRINT
"SHALL I TELL YOU A JOKE?"
20
INPUT
A$
30
IF
A$="GET LOST"
THEN GOTO
200
40
PRINT
"HOW MANY LEGS HAS A HORSE GOT?"
50
INPUT
LEGS
60
IF
LEGS=6
THEN GOTO
100
70
PRINT
"NO, 6, FORE LEGS IN FRONT","AND TWO BEHIND."
80
STOP
100
PRINT
"YES",,"SHALL I TELL YOU IT AGAIN?"
110
GOTO
20
200
PRINT
"ALL RIGHT, THEN, I WONT."
Before we discuss the
IF
statement, you should first look at the
STOP
statement in line 80: a
STOP
statement stops the execution of the program, giving report 9.
Now as you can see, an
IF
statement takes the form
IF
condition
THEN
statement
The statements here are
GOTO
statements, but they could be anything at all, even more
IF
statements.
The condition is something that is going to be worked out as either true or false; if it comes out as true then
the statement after
THEN
is executed, but otherwise it is skipped over.
The most useful conditions compare two numbers or two strings: they can test whether two numbers are
equal, or whether one is bigger than the other; & can test whether two strings are equal, or whether one
comes before the other in alphabetical order. They use the relations =, <, >,
<=
,
>=
and
<>
.
=, which we have used twice in the program (once for numbers & once for strings) means 'equals'. It is
not the same as the = in a
LET
statement.
< means 'is less than', so that
1<2
-2<-1
& -3<1
are all true, but
1<0
& 0<-2
are false.
To see how this works, let us write a program to input numbers & display the biggest so far.
10
PRINT
"NUMBER","BIGGEST SO FAR"
20
INPUT
A
30
LET
BIGGEST=A
40
PRINT
A,BIGGEST
50
INPUT
A
60
IF
BIGGEST<A
THEN LET
BIGGEST=A
70
GOTO
40
The crucial part is line 60, which updates BIGGEST if its old value was smaller than the new input
number A.
> (shifted M) means 'is greater than', & is just like < but the other way round. You can remember which