Tuesday, February
19 Week 6
Chapter 5
Student Notes
Objectives
Discuss project 4
Boolean Expressions and IF statements
Swapping
Multiple IF statements
1. Why use an
IF statement?
2. Ex,
finding yesterday and tomorrow
·
Ex. program 5.1
·
Why use IF Today =
Days’First THEN
Yesterday :=
Days’Last ;
ELSE
Yesterday := Days’Pred(Today);
END IF;
When we could just Monday
and Sunday?
3. Boolean
Expressions and Conditions
·
There are only two possible outcomes of a Boolean expression:
·
·
Some Boolean expressions are called
·
·
We use Conditions to compare one thing to another. All of conditions
follow one of two patterns:
variable relational
operator variable
variable relational
operator constant
·
Relational operators are familiar logical operators:
< (less than)
<= (less than or equal to)
> (greater
than)
>= (greater than or equal to)
= (equal
to)
/= (not equal to)
·
Notice that greater than or equal to
is >= and not =>
5.
Enumeration types and Conditional statements
·
When using conditionals with enumeration types, decisions are made
based on the order of the definition so for the following two enumeration
types:
TYPE Days IS (Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday, Sunday);
TYPE Colors IS (Red,
All of these statements
evaluate to true:
Monday < Tuesday
Wednesday /= Thursday
Wednesday = Wednesday
Wednesday >= Tuesday
Purple > Red
Yellow < Green
Green >= Yellow
·
The following statements would cause compilation errors because the two
values in each comparison are of different types:
Purple > Friday
3 <= 4.5
Green > 2
6. Two ways
to use an IF statement
·
IF condition THEN
statement sequence T
ELSE
Statement
sequence F
END IF;
·
·
·
·
IF condition THEN
statement sequence T
END IF;
7. Swapping
·
IF X
> Y THEN
Temp := X;
-- Store old X in a temp variable
X := Y; -- Store old Y in X
Y := Temp; -- Y now holds the old value of X
END
IF;
8. The
Multiple-Alternative IF statement
IF Response = Strawberry THEN
Straw := Straw + 1;
ELSIF Response = Chocolate THEN
Choc := Choc +1;
ELSIF Response = Vanilla THEN
Van := Van +1;
ELSE
Other := Other +1;
END IF;
·
Multiple IF statements evaluate from the top down. You can use this to
your advantage at times.
·
All Multiple IF statements should end with an ELSE statement, not an
ELSIF. Sometimes this takes a little clever thinking on the part of the
programmer.