Selection (if)
Programs so far are sequential and always operate the same way.
What happens when you get up in the morning?
Wake up.
Put on favorite t-shirt.
Eat breakfast.
What if it is cold?
"if" allows you to decide among alternatives.
Wake up.
If it is warm
put on favorite t-shirt.
Else put on sweater.
Eat breakfast.
One way selection:
if (condition)
action
example
Relational operators:
(condition) is a logical expression that is true or false.
e.g. (age > 62)
Values can be compared using relational operators > < = =
>= <= !=
temp = = 70
temp != 70
(2+5 ) < 3 //false but correct syntax
Possible pitfall:
if (age = = 21)
cout << "Voter!" << endl;
if (age = 21) //this assigns 21 to age and becomes true
cout << "Voter!" << endl;
Two way selection:
if (condition)
statement1
else
statement2;
examples: 1, 2
Logical operators && (AND) || (OR) ! (NOT):
Temperature between 70 and 80:
(temp >= 70) && (temp <= 80)
How to express below 70 or over 80:
(temp < 70) || (temp > 80)
!((temp >= 70) && (temp <= 80))
How would you express:
older than 25 and between 63 and 67 inches
older than 25 but not taller than 67 inches
between 25 and 27 or between 63 and 65 inches
What about this: (age > 62 || < 21)
Boolean variables:
Assigned a value true or false
bool pleasant;
pleasant=true;
...
Boolean variables can make a program more readable:
bool pleasant;
pleasant = (temp > 70) && (temp < 80);
if (pleasant)
{ ...
if2.cpp
Relational operators with floating point:
float x;
float y;
x = 1.0/3.0;
y = 1.0;
(3.0*x == y) //false!
(fabs( 3.0*x - y) < 0.0001) //true
float.cpp
Nested if:
nest0.cpp.
Getting dressed again:
WARM COLD
WEEKDAY t shirt sweater
WEEKEND black dress black dress
nest1.cpp.
Using booleans: nest2.cpp.
Checking for valid data:
We want temp > 0 and < 100.
if (temp >0 & < 100) ...?
nest3.cpp.
Sometimes used for multiway branches:
nest4.cpp.
There is a better way in Ch12.
Dangling else (a reason to use braces):
What does this mean?
if (temp > 70) sunny\temp 50 80
if (sunny)
cout << "shorts"; true shorts ?
else false ? ?
cout << "slacks";
Which matches?
if (temp > 70)
{
if (sunny)
cout << "shorts";
else
cout << "slacks";
}
or
if (temp > 70)
{
if (sunny)
cout << "shorts";
}
else
cout << "slacks";
Note indenting.