Chapter 5 Selection

Chapter 5
Selection
5-1
Selection (Decision)
The second control logic structure is selection:
Selection – Choosing between two or more alternative actions.
Selection statements alter the sequential flow of instructions in a program.
This is done using selection statements. When we make the computer
choose between two alternatives we will define one of the alternatives as
begin true and the other as being false. This choice will be made using a
boolean expression.
Boolean Expression – an expression that evaluates to either true or false
When boolean expressions are formed they must set up a relationship
between items in the expression. This relationship is set up using a set of
operators called the relational operators.
Relational Operators:
== (equal)
< (less than)
> (greater than)
<= (less than or equal)
>= (greater than or equal)
!= (not equal)
NOTE: The assignment operator is (=) but the relational operator is(= =).
In other words, if you are assigning a value to a variable, use (=) but if you
are asking whether two things are equal, use (= =).
5-2
Comparing Floating Point Numbers
It is common to use numeric values in decision statements. Due to the way
floating point numbers are stored in memory, do not compare two floating
point values for equality. Floating point numbers must be rounded when
they are stored in memory and rarely evaluate to be exactly the same. What
we want to do is check to see if they are close enough to equal for us to call
them equal. One easy method for doing this is to compare the absolute value
of the difference of the numbers with some very small epsilon value. Given
the following
const float EPSILON = 0.00001;
float val1, val2;
if (fabs(val1 - val2) < EPSILON)
{
cout << "values are equal";
}
fabs is a C++ library function that returns the absolute value of a floating
point expression.
5-3
Examples of boolean expressions:
Expression
Result
5 == 5
TRUE
‘a’ < ‘c’ TRUE
4 + 3 > 10 FALSE
10 != 20 TRUE
6 <= 6
TRUE
5 >= 9
FALSE
‘A’ < ‘Z’ TRUE
‘a’ < ‘Z’ FALSE (WHY?)
Given two variables n1 and n2, assume n1 contains 5 and n2 contains 3.
Evaluate each of the following boolean expressions:
n1 + 3 != n2 + 5
n1 * 2 <= n2 * 2
n1 >= n2
n2 <= n1
n2 + n1 + 3 == n1 + 6
The precedence order when the relational operators are added is as follows:
* / %
+ < <= > >=
== !=
=
Parentheses may be used to alter the order of evaluation.
5-4
The C++ If-Then and If-Then-Else Statements
The use of the If-Then and If-Then-Else statements in a program allows the
programmer to include all possible options in the program code and the
computer to select the appropriate option during program execution.
Flowchart for the If-Then statement
boolean
expression
T
F
statement
The boolean expression is evaluated and if it evaluates to TRUE the
statement inside the If is executed and the program continues to the next
executable statement. If the expression evaluates to FALSE, the statement
inside the If is ignored and the program continues with the next executable
statement.
GENERAL FORM of the If-Then statement:
if (boolean expression)
{
statement;
}
5-5
T
hours <= 40
output “No overtime”
F
if (hours <= 40)
{
cout << “No overtime” << endl;
}
cout << “Continue” << endl;
Given a value of 25 in the location hours, the program would output
No overtime
Continue
If location hours contained the value 50, the program would output
Continue
5-6
Nested If-Then Statements
A nested If-Then is an If-Then that contains another If-Then within it.
Suppose we wanted to identify 18 year old males. We could first determine
whether the age requirement was met and if so, check to see whether the
individual is a male.
Outer If
age == 18
T
T
Inner If
F
sex == ‘M’
output “The Marine Corps is
F
looking for a few good men.”
if (age == 18)
{
if (sex == ‘M’)
{
cout << “The Marine Corps is looking for a few good men.”;
}
}
5-7
The If-Then-Else Statement
In the If-Then statement a condition was evaluated and if the condition was
true, an instruction was executed and the program continued on, if the
condition was false, the program simply continued on. The If-Then-Else
statement assures that some action will take place before the program
continues. If the condition is true then do this else do that.
GENERAL FORM If-Then-Else Statement
if (Expression)
{
statement 1;
}
else
{
statement 2;
}
Flowchart for If-Then-Else
F
boolean
expression
statement 2
T
statement 1
5-8
Example:
F
T
hours <= 40
output “overtime due”
output “no overtime”
C++ code:
if (hours <= 40)
{
cout << “no overtime”;
}
else
{
cout << “overtime due”;
}
It is possible to “nest” If-Then-Else statements just as we did with If-Then
statements.
5-9
If-Then-Else Exercise
1.) Draw the flowchart for a program that will receive three integers from
the user. Your program is to output the largest of the three. We will assume
that the three values are not equal. KEEP THIS AS AN EXAMPLE OF
THE CORRECT FLOWCHART STYLE FOR NESTED IF/ELSE
STATEMENTS.
5-10
The Conditional Operator
The conditional operator is a “shortcut” method that may be used to create
simple if/else expressions.
GENERAL FORM:
Expression ? expression : expression;
Example:
overTime = hrsWkd > 40 ? (hrsWkd-40)*rate*1.5 : 0.0;
The part of the conditional expression that precedes the ? is the expression to
be tested (like the expression in parentheses in an if statement). If the
expression is true, the statement between the ? and : is executed otherwise
the expression after the : is executed. The statement above could replace the
block if shown below.
if (hrsWkd > 40)
overTime = hrsWkd-40) * rate * 1.5;
else
overTime = 0.0;
or even
cout << “Overtime is “ << (hrsWkd > 40 ? (hrsWkd-40)* rate * 1.5 : 0.0);
5-11
Logical/Boolean Operators and Expressions
George Boole’s The Mathematical Analysis of Logic was published in 1847.
The formal axioms of logic were set forth in this book and the field of
symbolic logic was built. This logic eventually formed the basis for the
development of digital computers. We will use the boolean operators to form
complex decision statements.
NOT
AND
OR
!
&&
||
unary operator
binary operator
binary operator
By using these operators in conjunction with the relational operators, more
complex expressions may be formed.
NOT (!)
precedes a single expression and gives its opposite as the result.
hrsWkd <= 40
is equivalent to
!(hrsWkd > 40)
5-12
AND (&&) combines two logical expressions and requires that both
expressions be TRUE for the entire expression to be TRUE
num1 <= 10 && num1 != 5
The value of num1 would need to be less than or equal to 10 and also not
equal to 5 for this expression to be TRUE
OR (||)
combines two logical expressions and states that if either or
both of the expressions are TRUE, the entire expression is TRUE
num1 <1 || num1 > 10
If the value of num1 is not in the range 1-10 this expression evaluates to
TRUE
Rewrite the following expressions:
!(num1 == num2)
!(num1 == num2 || num1 == num3)
!(num1 == num2 && num3 > num4)
5-13
In math books the notation
5 < x < 15
is common. It means that x is between 5 and 15. While the expression is
legal in C++ the result is unexpected. What is the result and why?
How should the expression be written?
5-14
Short-Circuit Evaluation: Evaluation of a logical expression in left-toright order with evaluation stopping as soon as the final truth can be
determined.
When AND is used in an expression, the computer stops evaluation as soon
as a FALSE condition is found. When OR is used in an expression,
evaluation can stop as soon as the first TRUE condition is found. Some
languages use full evaluation of logical expressions where both
subexpressions are evaluated before the && or || operator is applied.
Precedence of Operators
()
++ -!
* / %
+ < <= > >=
== !=
&&
||
=
Highest
Lowest
5-15
Exercises
1 Given the following values for variables a, b and c:
a = TRUE
b = FALSE
c = TRUE
evaluate each of the following expressions
a) a && b || a && c
b) !(a && c) || b
c) !a || c && b
2. Rewrite the following expressions so they would be valid in C++.
a) a, b and c are all less than 10
b) a > b >= c
c) a does not equal either b or c
d) a equals b but does not equal c
5-16
Boolean Expressions Programming Exercise
A military academy accepts candidates according to the following height
and weight requirements.
Gender
Male
Female
Min. Height
62 in.
60 in.
Max. Height
78 in.
72 in.
Min. Weight
130 lbs.
110 lbs.
Max. Weight
250 lbs.
185 lbs.
Design a program that accepts as input the gender, height and weight of a
candidate. Check to see if the candidate meets the height requirements and
store the result in a bool variable called heightOk. Next check the weight
requirements and store the result in a bool variable called weightOk. Using
these results, determine whether the candidate was accepted, rejected for
height only, rejected for weight only or rejected for both height and weight.
Output an appropriate message for each possible outcome.
5-17
Multi-way Selection
The switch statement in C++ provides a way to eliminate some nested if
structures. The general form for the switch statement is
switch (IntegralExpression)
{
SwitchLabel…statement;
.
.
}
The general form for the SwitchLabel is
case ConstantExpression:
default:
where
•
•
•
•
•
The switch expression is the expression whose value determines which label is
selected. It cannot be a floating point expression.
The SwitchLabel is either a case label or a default label. In the case label, the
ConstantExpression must be an integral literal or a named constant.
Each case constant may appear only once in the statement.
The switch expression is evaluated and if the value matches one of the constants in
the case label, control branches to to the statement following the label. From there it
proceeds sequentially until the end of the switch statement or until a break is
encountered.
If there is no matching label for the expression, it looks for a default label and if
found, executes the statement following the label. If no default label is present,
control transfers to the statement following the end of the switch statement.
5-18
Example:
classCode
‘F’
Freshman
‘S’
Sophomore
‘J’
‘R’
Junior
Senior
default
Invalid
switch (classCode)
{
case ‘F’ : cout << “You are a freshman”;
break;
case ‘S’ : cout << “You are a sophomore”;
break;
case ‘J’ : cout << “You are a junior”;
break;
case ‘R’ : cout << “You are a senior”;
break;
default : cout << “You entered an invalid code”;
break; // not necessary but a good habit
}
5-19
The fact that without the break statement, the program “follows through”
can be helpful in some situations. Suppose we wanted to allow for lower
case input as well.
switch (classCode)
{
case ‘F’ :
case ‘f’ : cout << “You are a freshman”;
break;
case ‘S’ :
case ‘s’ : cout << “You are a sophomore”;
break;
etc.
Switch Exercises:
1. Flowchart a code segment that reads a letter grade from the keyboard and
prints “good work” for A and B students, “average work” for C students,
and “poor work” for D and F students. Draw this flowchart as a nested
if.
2 Write the C++ code to match the flowchart from #1.
3 Draw the flowchart to convert the nested if into a switch statement.
4 Write the C++ code for the flowchart from #3.
5-20