Lecture 11: Control Flow.
Selection (Decision) structures
(cont)
Lecture Contents:
switch statement
The
Demo programs
Exercises
2
Control Structures
Three methods of processing a program
– In sequence
– Branching
– Looping
.
Branch: altering the flow of program
execution by making a selection or choice
Loop: altering the flow of program
execution by repetition of statement(s)
3
3
Flow of Execution
.
4
4
Reminder
Single (one-way) selection
Double (two-way) selection
The if statement (then version)
Syntax and flowchart fragment:
if (<expression>) <statement>;
6
The if statement (then – else
version)
Syntax and flowchart fragment:
if (<expression>) <statement_1>;
else <statement_2>;
7
New
Multiple selection
Multiple selection
9
The switch statement
Syntax and flowchart fragment:
The switch statement: If you have a large
decision tree and all the decisions depend on
different values of the same variable (control
expression) you’ll probably want to consider a
switch statement instead of a series of
nested if…else if…else statements or
alternate sequence of if statements.
10
The switch statement
Syntax&flowchart fragment in general:
switch ( <control expression> )
{
case <const_express1>: <stmts1>; break;
case <const_express2>: <stmts2>; break;
...
case <const_expressn>: <stmtsn>; break;
default:
<statementsd>; break;
};
Don’t forget the break statement: Without it control passes down to (or
falls through) the statements for the next case which is usually not
what you want
11
The switch statement
What is <constant expression> ?
It’s an expression that may be evaluated at compile
time.
In other words, all operands must be with fixed,
defined values during the compilation process.
See examples on next slide(s)
12
The switch statement
What is <constant expression> ?
Expression whose operands are literal values:
YES
– 5+6*8
– 10 * (4 +16) – 5
– 100 % 5 + 20 / 5
13
The switch statement
What is <constant expression> ?
Expression whose operands are constant
(const), i.e. named constant: YES
– const int A = 15;
– 5+A*8
const int B = 24;
– 10 * (A + B) – 5
– 100 % A + 20 / B
14
The switch statement
What is <constant expression> ?
Expression whose operands are standard scalar
variables: NO/YES
– int a=15;
– 5+a*8
int b=24;
– 10 * (a + b) – 5
– 100 % a + 20 / b
15
The switch statement
What is <constant expression> ?
Expression whose operands are standard scalar
variables: NO
– int a;
int b;
cin >> a >> b;
– 5+a*8
– 10 * (a + b) – 5
– 100 % a + 20 / b
16
The switch statement
Example:
int speed;
cout<<“\nEnter 33, 45 or 78:”; cin>>speed;
switch(speed)
{
case 33: cout<<”Long play album”; break;
case 45: cout<<”Single selection”; break;
case 78: cout<<”Obsolete format”; break;
default: cout<<”Wrong value entered”;
};
Reminder: Don’t forget the break statement: Without it control passes down to (or falls through)
the statements for the next case which is usually not what you want
17
More on switch statement
Extract from Friedman/Koffman 4e
chapter 4
18
Selection Structures: if and
switch Statements
Chapter 4
Selection Statements
– In this chapter we study statements that allow
alternatives to straight sequential processing. In
particular:
• if statements (do this only if a condition is true)
• if-else statements (do either this or that)
• Logical expressions (evaluate to true or false)
• Boolean operators (not: ! and: && or: ||)
• Bit-wise boolean operators (and: & or: |)
20
Logical Expressions
– Logical expressions often use these relational
operators:
>
<
>=
<=
==
!=
Greater than
Less than
Greater than or equal
Less than or equal
Equal
Not equal
21
Truth Tables for Boolean
Operators
Truth tables Logical operators !, ¦¦, &&
– 1 is a symbol for true
– 0 is a symbol for false
Operation
! 0
! 1
Result
1
0
Operation
1 ¦¦ 1
1 ¦¦ 0
0 ¦¦ 1
0 ¦¦ 0
Result
1
1
1
0
Operation
1 && 1
1 && 0
0 && 1
0 && 0
Result
1
0
0
0
22
Precedence of Operators
Highest
Unary
Multiplicative
Additive
Input/Output
Relational
Equality
and
or
Assignment
Operator
Description
Grouping
::
()
!,
*
+
>>
<
<=
==
&&
¦¦
=
Scope resolution
Function call
Not, unary plus/minus
Multipy/divide/remainder
Binary plus, minus
Extraction / insertion
Less/Greater than
Less/Greater or equal
Equal, Not equal
Logical and
Logical or
Assign expression
Left to right
+, / %
<<
>
>=
!=
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
23
4.8 The switch Control
Statement
switch ( switch-expression )
{
case value-1 :
statement(s)-1
break ;
. . .
// many cases are allowed
case value-n :
statement(s)-n
break ;
default :
default-statement(s)
}
24
Switch Control
– When a switch statement is encountered,
the switch-expression is evaluated. This
value is compared to each case value
until switch-expression == case value.
All statements after the colon : are
executed
– It is important to include the break
statement
25
Example switch Statement:
switch(watts) // Assume char option = '?’
{
case 25:
cout << " Life expectancy is 2500 hours. " << endl; break;
case 40:
case 60:
cout << " Life expectancy is 1000 hours. " << endl; break;
case 75:
case 100:
cout << " Life expectancy is 750 hours. " << endl; break;
default: cout << "Invalid Bulb !!" << endl;
}; // end switch
26
Trace the previous switch
– Show output when
• watts = '?'
____________?
• watts = 40
____________?
• watts = 10
____________?
• watts = 200
____________?
• watts = 100
____________?
27
Before lecture end
Lecture:
Control Flow. Selection (decision) structures
More to read:
Friedman/Koffman, Chapter 04
28
Chapter 4:
Selection Structures: if and switch Statements
Problem Solving,
Abstraction, and Design using C++ 5e
by Frank L. Friedman and Elliot B. Koffman
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.8 The switch Control Statement
switch ( switch-expression )
{
case label1: statements1;
break;
case label2: statements2;
break;
.
.
.
case labeln: statementsn;
break;
default: statementsd;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
// optional
30
Switch Control Statement
• Alternative to multiple if statements in
some cases
• Most useful when switch selector is single
variable or simple expression
• Switch selector must be an integral type
(int, char, bool)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
31
Switch Control Statement
• Switch selector value compared to each
case label. When there is an exact match,
statements for that case are executed.
• If no case label matches the selector, the
entire switch body is skipped unless it
contains a default case label.
• break is typically used between cases to
avoid fall through.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
32
Listing 4.5
switch statement to determine life
expectancy of a lightbulb
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
33
4.9 Common Programming Errors
• Use parentheses to clarify complex
expressions
• Use logical operators only with logical
expressions
• Use braces { } to group multiple statements
for use in control structures
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
34
Common Programming Errors
• When writing a nested if statement, use
multiple-alternative form if possible
– if conditions are not mutually exclusive, put the
most restrictive condition first
• Make sure switch selector and case labels
are the same type.
• Provide a default case for a switch
statement whenever possible.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
35
Decision Tree
Figure 5-7 Bonus decision tree
C# Programming: From Problem Analysis to Program Design
36
Decision Tables
• Decision tables are a precise yet compact
way to model complicated logic.
• Decision tables, like flowcharts and if-thenelse and switch-case statements, associate
conditions with actions to perform, but in
many cases do so in a more elegant way.
Decision Tables
The four quadrants
Conditions
Condition alternatives
Actions
Action entries
Each decision corresponds to a variable, relation or
predicate whose possible values are listed among the
condition alternatives. Each action is a procedure or
operation to perform, and the entries specify whether
(or in what order) the action is to be performed for the
set of condition alternatives the entry corresponds to.
Decision Tables
Decision Tables
Conditions
Rules
Actions/Activities
Conditions
Rules
C1. Qual > 10 years
Y
Y
Y
Y
N
N
N
N
C2. Gender – male
Y
Y
N
N
Y
Y
N
N
C3. Age > 50
Y
N
Y
N
Y
N
Y
N
900
700
800
600
0
0
0
0
Actions
A1. Extra payment
7/13/2017
Таблици на решение
Стих: древноперсийски епос:
Този, който не знае и не знае, че не знае,
Той е глупак, бягай от него!
Този, който не знае и знае, че не знае,
Той може да се изучи, помогни му!
Този, който знае и не знае, че знае,
Той спи, събуди го!
Този, който знае и знае, че знае,
Той е пророк(мъдрец), учи се от него!
7/13/2017
Таблицы Решений
В древнем персидском стихотворении сказано:
Тот, кто не знает и не знает, что он не знает,
- глупец, избегай его.
Тот, кто не знает и знает, что он не знает,
может научиться, научи его.
Тот, кто знает и не знает, что он знает,
спит, разбуди его,
Тот, кто знает и знает, что он знает,
- пророк, учись у него.
7/13/2017
Decision Tables
Version in English presented as Jewish proverb:
He who knows not and knows not he knows not,
he is a fool, shun him.
He who knows not and knows he knows not,
he is ignorant, teach him.
He who knows and knows not he knows,
he is asleep, awaken him.
He who knows and knows he knows,
he is wise, follow him.
7/13/2017
Decision Tables
Conditions
Rules
C1. Man knows
N
N
Y
Y
C2. Man knows, that C1
N
Y
N
Y
Actions
A1. SHUN HIM!
A2. TEACH HIM
A3. AWAKEN HIM!
A4. FOLLOW HIM!
7/13/2017
X
X
X
X
44
Exercises
• Write a C# program that corresponds to the
extra payment decision table.
Exercise 11.1
Build programs based on branch
algorithms using the switch statement:
To test an input integer value entered
from the keyboard as a valid speed of a
gramophone (obsolete record player) –
33, 45, 78;
46
Exercise 11.2
Build programs based on branch algorithms
using the switch statement:
To test a character as a valid grade
‘A’ or ‘a’ - excellent
‘B’ or ‘b’ - good
‘C’ or ‘c’ - average
‘D’ or ‘d’ - poor. Student is to retake.
47
Exercise 11.3
Build programs based on branch algorithms
using the switch statement:
To classify the type of a ship through its
class identifier:
‘B’ or ‘b’ - Battle ship
‘C’ or ‘c’ - Cruiser
‘D’ or ‘d’ - Destroyer
‘F’ or ‘f’ - Frigate
48
Exercise 11.4
Build programs based on branch algorithms using the
switch statement:
To associate the expected brightness of a
standard light bulb depending on its power
(wattage);
Watts
15
25
40
60
75
100
Brightness (in lumens)
125
215
500
880
1000
1675
49
Exercise 11.5
Build programs to test logical operators
negation
conjunction
disjunction
50
Exercise 11.6
Build programs to test the bit wise And (&)
operator
Build programs to test the bit wise Or ( | )
operator
51
Thank You
For
Your Attention!
52
© Copyright 2026 Paperzz