Selection:
IF...ELSE
An if...else
statement works in a similar way
to an if
statement, except that it also
provides a statement to be executed if the test is false.
Using pseudocode code we can illustrate
how an if..else
statement works. The general form of an if...else
statement is as follows:
if(
test )
statement
to execute if test was true
else
statement
to execute if test was false
Let us extend our pseudocode design for
the fire alarm from Unit 3, making the device flash a green light if all
is well (i.e. if the temperature is not too high):
if
( temperature to high )
sound
the alarm
else
display
a flashing green light to show alarm is working
This might be implemented in Java as follows:
if
(temperature > 78)
soundAlarm();
else
displayFlashingLight(
green );
The way an if...else
statement can cause deviation from
the default sequential flow of execution can be illustrated as follows.
Consider this pseudocode design:
statementA;
if(
age > 60 )
statementB;
else
statementC;
statementD;
If the variable
age
has a value over 60, say 65, then
the test ( age
> 60 ) will be true,
and the therefore statementB
will be executed. So the statements
to be executed will be:
statementA
statementB
statementD
However, if the variable
age
has a value of 60 or less, say
21, then the test ( age
> 60 ) will be false,
and statementB
will not be executed. However,
since the test is false the statement after else
will be executed. So the statements
executed will be:
statementA
statementC
statementD
Thus the result of an if...else
selection statement
means that either
one or some other statement(s) will be executed,
but
not both.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|