Chapter 3 Selection Statements: Lecturer: Mrs Rohani Hassan
Chapter 3 Selection Statements: Lecturer: Mrs Rohani Hassan
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X
1
Objectives
To declare bool type and write Boolean expressions using
comparison operators (§3.2).
To implement selection control using simple if statements (§3.3).
To combine conditions using logical operators (&&, ||, and !)
(§3.4).
To implement selection control using if ... else statements (§3.5).
To implement selection control using nested if statements (§3.6).
To implement selection control using switch statements (§3.9).
To write expressions using the conditional operator (§3.10).
To display formatted output using the stream manipulators
(§3.11).
To know the rules governing operand evaluation order, operator
precedence, and operator associativity (§3.12).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X
2
The bool Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j. C++
provides six relational operators (also known as
comparison operators) in Table 3.1 that can be
used to compare two values.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
3
Comparison Operators
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
4
Simple if Statements
if (radius >= 0)
if (booleanExpression) {
{ area = radius * radius * PI;
statement(s);
} cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
}
false false
Boolean (radius >= 0)
Expression
true true
(a) (b)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5
Note
Outer parentheses required Braces can be omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) if ((i > 0) && (i < 10))
Equivalent
{ cout << "i is an " <<
cout << "i is an " << "integer between 0 and 10";
"integer between 0 and 10";
}
(a) (b)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
6
Examples
Listing 3.1 gives a program that checks whether a number is even or
odd. The program prompts the user to enter an integer (line 9) and
displays “number is even” if it is even (lines 11-12) and “number is
odd” if it is odd (lines 14-15).
TestBoolean Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
7
Caution
Adding a semicolon at the end of an if clause is a
common mistake.
Logic Error Empty Body
GuessBirthDate Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
9
Boolean Operators
Operator Name
! not
&& and
|| or
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
10
Truth Table for Operator !
p !p Example
true false !(1 > 2) is true, because (1 > 2) is false.
false true !(1 > 0) is false, because (1 > 0) is true.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
11
Truth Table for Operator &&
p1 p2 p1 && p2 Example
false false false (3 > 2) && (5 >= 5) is true, because (3 >
false true false 2) and (5 >= 5) are both true.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
12
Truth Table for Operator ||
p1 p2 p1 || p2 Example
false false false (2 > 3) || (5 > 5) is false, because (2 > 3)
false true true and (5 > 5) are both false.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
13
Examples
Listing 3.3 gives a program that checks whether a number is
divisible by 2 and 3, whether a number is divisible by 2 or 3, and
whether a number is divisible by 2 or 3 but not both:
TestBooleanOperators Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
14
Short-Circuit Operator
When evaluating p1 && p2, C++ first evaluates p1 and then
evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2.
When evaluating p1 || p2, C++ first evaluates p1 and then evaluates
p2 if p1 is false; if p1 is true, it does not evaluate p2. Therefore, &&
is referred to as the conditional or short-circuit AND operator, and ||
is referred to as the conditional or short-circuit OR operator.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
15
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true false
Boolean
Expression
Statement(s) for the true case Statement(s) for the false case
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
16
Examples
Listing 3.4 presents a program that lets the user enter a year and
checks whether it is a leap year.
LeapYear Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
17
Nested if Statements
if (i > k)
{
if (j > k)
cout << "i and j are greater than k";
}
else
cout << "i is less than or equal to k";
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
18
Multiple Alternative if Statements
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
19
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
20
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
21
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
22
animation
Trace if-else statement
Suppose score is 70.0 grade is C
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
23
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
24
Note
The else clause matches the most recent if clause in the
same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
Equivalent
int k = 3; int k = 3;
if (i > j) if (i > j)
if (i > k) This is better if (i > k)
cout << "A"; with correct cout << "A";
else indentation else
cout << "B"; cout << "B";
(a) (b)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
25
Note, cont.
Nothing is printed from the preceding statement. To force the else
clause to match the first if clause, you must add a pair of braces:
if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
26
TIP
if (number % 2 == 0) Equivalent
even = true; bool even
else = number % 2 == 0;
even = false; This is better
(a) (b)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
27
CAUTION
Equivalent if (even)
if (even == true)
cout <<"It is even."; cout << "It is even.";
(a) (b)
This is better
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
28
Example: Computing Taxes
The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2002
are shown in Table 3.6.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
29
Example: Computing Taxes, cont.
if (status == 0)
{
// Compute tax for single filers
}
else if (status == 1)
{
// Compute tax for married file jointly
}
else if (status == 2)
{
// Compute tax for married file separately
}
else if (status == 3)
{
// Compute tax for head of household
}
else
{
// Display wrong status
}
ComputeTaxWithSelectionStatement Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
30
Example: A Simple Math Learning Tool
This example creates a program for a first grader to practice
subtractions. The program randomly generates two single-digit
integers number1 and number2 with number1 > number2 and
displays a question such as “What is 9 – 2?” to the student, as
shown in the sample output. After the student types the answer, the
program displays a message to indicate whether the answer is
correct.
SubtractionTutor Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
31
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
32
switch Statement Flow Chart
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
33
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the
…
value of the switch-expression.
The resulting statements in the case valueN: statement(s)N;
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch-
}
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
34
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end of
case value1: statement(s)1;
each case in order to terminate the
remainder of the switch statement. break;
If the break statement is not case value2: statement(s)2;
present, the next case statement
will be executed. break;
…
case valueN: statement(s)N;
The default case, which is break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the
specified cases matches the }
switch-expression. The case statements are executed in sequential
order, but the order of the cases (including the
default case) does not matter. However, it is good
programming style to follow the logical sequence of
the cases and place the default case at the end.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
35
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
36
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
37
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
38
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
39
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
40
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Next statement;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
41
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
42
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
43
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
44
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
45
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
Next statement;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
46
Conditional Operator
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(booleanExpression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
47
Conditional Operator
cout << ((num % 2 == 0) ? "num is even" :
"num is odd");
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
48
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
49
Formatting Output
Operator Description
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
50
Operator Precedence
How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
51
Operator Precedence
var++, var--
+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and
remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
52