Flow of Control
Contents
o Boolean Expression
o Control Structures
o if .. else Statements
o switch Statement
o while Structure
o do .. while Structure
o for Structure
fit@hcmus | Programming 1 | 2021 2
Boolean Expressions
fit@hcmus | Programming 1 | 2021 3
Boolean Expression
o Boolean expression: an expression that is either true or false.
o Comparison Operators: == , !=, <, <=, >, >=
fit@hcmus | Programming 1 | 2021 4
Comparison Operators
fit@hcmus | Programming 1 | 2021 5
Building Boolean Expressions
o Combine two comparisons using:
• AND operator: &&
( Boolean_Exp_1) && (Boolean_Exp_2)
• OR operator: ||
( Boolean_Exp_1) || (Boolean_Exp_2)
o Negate a Boolean expression, NOT operator: !
!( Boolean_Exp)
fit@hcmus | Programming 1 | 2021 6
Evaluating Boolean Expressions
o Be evaluated the same way as arithmetic expressions.
o Examples:
bool result = (x < z) && (z < y);
!( (y < 3) || (y > 7))
o Rules: truth tables.
o true, false: predefined constants of type bool.
fit@hcmus | Programming 1 | 2021 7
Precedence Rules
o Boolean expression need not be fully parenthesized.
o Default precedence:
• First: !
• Next: relational operations (<, >,..)
• Next: &&
• Next: ||
o Examples:
• (temperature > 80) && (humidity > 0.9) && (poolGate == OPEN)
• temperature > 80 && humidity > 0.9 && poolGate == OPEN
fit@hcmus | Programming 1 | 2021 8
Precedence of Operators
fit@hcmus | Programming 1 | 2021 9
Precedence of Operators
fit@hcmus | Programming 1 | 2021 10
Precedence Rules
o short-circuit evaluation: if it gets enough information to determine the
value, it does not bother to evaluate other expressions.
• C++ uses this way.
o complete evaluation: all the expressions are evaluated before
determining.
• Some of the languages.
o Examples:
(age >= 21) || ( x == 5) //Line 1
(grade == 'A') && (x >= 7) //Line 2
fit@hcmus | Programming 1 | 2021 11
Control Structures
fit@hcmus | Programming 1 | 2021 12
Control Structures
o A computer can proceed:
• In sequence
• Selectively (branch) - making a choice
• Repetitively (iteratively) - looping
o Some statements are executed only if certain conditions are met
o A condition is met if it evaluates to true
fit@hcmus | Programming 1 | 2021 13
Control Structures
fit@hcmus | Programming 1 | 2021 14
Selection Structures
o if-else statements
o switch-case statements
fit@hcmus | Programming 1 | 2021 15
Repetition Structures
o while ... do
o do ... while
o for
fit@hcmus | Programming 1 | 2021 16
if-else Statements
fit@hcmus | Programming 1 | 2021 17
if-else Statements
NO YES
x < y?
Process A Process B
fit@hcmus | Programming 1 | 2021 18
One-Way Selection
o Syntax:
if (Boolean_Expression)
Yes_Statement
o The Yes_Statement is executed if the value of the
Boolean_Expression is true
o The statement is bypassed if the value is false; program goes to
the next statement.
o Example:
if (score >= 5.0)
pass = true;
fit@hcmus | Programming 1 | 2021 19
One-Way Selection
fit@hcmus | Programming 1 | 2021 20
One-Way Selection
o Some error examples:
//Syntax
• if score >= 60
grade = 'P’;
//Logical
• if (score >= 60);
grade = 'P';
fit@hcmus | Programming 1 | 2021 21
Two-Way Selection
o Two-way selection takes the form:
if (Boolean_Expression)
Yes_Statement
else
No_Statement
o If Boolean_Expression is true, Yes_Statement is executed;
otherwise, No_Statement is executed
• Yes_Statement and No_Statement are any C++ statements
fit@hcmus | Programming 1 | 2021 22
Two-Way Selection
fit@hcmus | Programming 1 | 2021 23
Two-Way Selection
fit@hcmus | Programming 1 | 2021 24
Compound Statements
o A list of statements enclosed in a pairs of braces.
o Compound statement (block of statements):
{
Statement_1;
Statement_2;
...
Statement_n;
}
o A compound statement is a single statement.
fit@hcmus | Programming 1 | 2021 25
Compound Statements
o Example:
if (age > 18)
{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}
fit@hcmus | Programming 1 | 2021 26
Multiple Selections: Nested if
o Nesting: one control statement in another
o An else is associated with the most recent if that has not been paired with an
else
o Syntax:
if (Boolean_Expression_1)
Statement_1
else if (Boolean_Expression_2)
Statement_2
...
else if (Boolean_Expression_n)
Statement_n
else
Statement_For_All_Other_Possibilities
fit@hcmus | Programming 1 | 2021 27
Multiple Selections: Nested if
fit@hcmus | Programming 1 | 2021 28
Multiple Selections: Nested if
fit@hcmus | Programming 1 | 2021 29
Confusion between == and =
o C++ allows you to use any expression that can be evaluated to
either true or false as an expression in the if statement:
if (x = 5)
cout << "The value is five." << endl;
o The appearance of = in place of == resembles a silent killer
• It is not a syntax error
• It is a logical error
fit@hcmus | Programming 1 | 2021 30
Conditional Operator (?:)
o Conditional operator (?:) takes three arguments
• Ternary operator
o Syntax for using the conditional operator:
expression1 ? expression2 : expression3
o If expression1 is true, the result of the conditional expression
is expression2
• Otherwise, the result is expression3
fit@hcmus | Programming 1 | 2021 31
switch Statement
fit@hcmus | Programming 1 | 2021 32
switch Statement
o switch structure: alternate to if-else
o switch (integral) expression (controlling expression) is evaluated
first.
o Value of the controlling expression determines which corresponding
action is taken.
fit@hcmus | Programming 1 | 2021 33
switch Statement
switch (Controlling_Expression)
{
case Constant_1:
Statement_Sequence_1
break;
case Constant_2:
Statement_Sequence_n
break;
...
case Constant_n:
Statement_Sequence_n
break;
default:
Default_Statement_Sequence
}
fit@hcmus | Programming 1 | 2021 34
fit@hcmus | Programming 1 | 2021 35
switch Statement
o One or more statements may follow a case label.
o Braces are not needed to turn multiple statements into a single
compound statement.
o The break statement may or may not appear after each
statement.
o switch, case, break, and default are reserved words.
fit@hcmus | Programming 1 | 2021 36
switch Statement
fit@hcmus | Programming 1 | 2021 37
switch Statement
fit@hcmus | Programming 1 | 2021 38
Enumeration Types
o Enumeration type: a type whose values are defined by a list of
constants type int.
o Syntax:
enum Name {enumerator_1, enumerator_2,...};
enum Name {enumerator_1 = constant_1, enumerator_2 =
constant_2,...};
o Examples:
• enum Direction {NORTH, SOUTH, EAST, WEST};
• enum Direction {NORTH=0, SOUTH=1, EAST=2, WEST=3};
• enum MyNum {ONE = 17, TWO, THREE, FOUR = -3, FIVE}
fit@hcmus | Programming 1 | 2021 39
Enumeration Types
o Example:
enum Color { red, green, blue };
Color r = red;
switch(r)
{
case red : std::cout << "red\n"; break;
case green: std::cout << "green\n"; break;
case blue : std::cout << "blue\n"; break;
}
fit@hcmus | Programming 1 | 2021 40
assert function
Terminating a Program with the assert Function
fit@hcmus | Programming 1 | 2021 41
Terminating a Program with the assert Function
o Certain types of errors that are very difficult to catch can occur in a
program
• Example: division by zero can be difficult to catch using any of the
programming techniques examined so far
o The predefined function, assert, is useful in stopping program
execution when certain elusive errors occur.
fit@hcmus | Programming 1 | 2021 42
The assert Function
o Syntax:
expression is any logical expression
o If expression evaluates to true, the next statement executes
o If expression evaluates to false, the program terminates and
indicates where in the program the error occurred
o To use assert, include cassert header file.
fit@hcmus | Programming 1 | 2021 43
The assert Function
o assert is useful for enforcing programming constraints during
program development.
o After developing and testing a program, remove or disable assert
statements.
o The preprocessor directive #define NDEBUG must be placed
before the directive #include <cassert> to disable the assert
statement.
fit@hcmus | Programming 1 | 2021 44
Programming Example
fit@hcmus | Programming 1 | 2021 45
Cable Company Billing
o This programming example calculates a customer’s bill for a local
cable company.
o There are two types of customers:
• Residential
• Business
o Two rates for calculating a cable bill:
• One for residential customers
• One for business customers
fit@hcmus | Programming 1 | 2021 46
Cable Company Billing - Rates
o For residential customer:
• Bill processing fee: $4.50
• Basic service fee: $20.50
• Premium channel: $7.50 per channel
o For business customer:
• Bill processing fee: $15.00
• Basic service fee: $75.00 for first 10 connections and $5.00 for each
additional connection
• Premium channel cost: $50.00 per channel for any number of connections
fit@hcmus | Programming 1 | 2021 47
Cable Company Billing - Requirements
o Ask user for account number and customer code
o Assume R or r stands for residential customer and B or b stands for
business customer.
o The program should print the billing amount to two decimal places
fit@hcmus | Programming 1 | 2021 48
Cable Company Billing - Input/Output
o Input:
• Customer account number
• Customer code
• Number of premium channels
• For business customers, number of basic service connections
o Output:
• Customer’s account number
• Billing amount
fit@hcmus | Programming 1 | 2021 49
Repetition Structures
fit@hcmus | Programming 1 | 2021 50
Why Is Repetition Needed?
o Repetition allows you to efficiently use variables
o Can input, add, and average multiple numbers using a limited
number of variables.
o For example, to add five numbers:
• Declare a variable for each number, input the numbers and add the
variables together
• Create a loop that reads a number into a variable and adds it to a variable
that contains the sum of the numbers
fit@hcmus | Programming 1 | 2021 51
Repetition Structures
o Three loop statements:
• while ... do
• do ... while
• for
o loop body: the code repeated in a loop.
o iteration: each repetition of a loop.
o Infinite loop: continues to execute endlessly
• Avoided by including statements in loop body that assure exit condition is
eventually false
fit@hcmus | Programming 1 | 2021 52
while Structures
fit@hcmus | Programming 1 | 2021 53
while Structure
o Single-statement body:
while (expression)
statement
o Multi-statement body:
while (expression)
{
Statement_1
Statement_2
...
Statement_Last
}
fit@hcmus | Programming 1 | 2021 54
while Structure
fit@hcmus | Programming 1 | 2021 55
while Structure
o Example:
int i = 0;
while (i <= 20)
{
cout << i << " ";
i = i + 5;
}
o Example:
int i = 20;
while (i < 20)
{
cout << i << " ";
i = i + 5;
}
fit@hcmus | Programming 1 | 2021 56
do..while Structure
o Single-statement body:
do
Statement
while (Boolean_Expression);
o Multi-statement body:
do
{
Statement_1
Statement_2
...
Statement_Last
} while (Boolean_Expression);
fit@hcmus | Programming 1 | 2021 57
do..while Structure
Statement_1
Statement_Last
YES
Boolean_Expression
NO
fit@hcmus | Programming 1 | 2021 58
do..while Structure
o Example:
int i = 0;
do
{
cout << i << " ";
i = i + 5;
} while (i <= 20);
o Example:
int i = 20;
do
{
cout << i << " ";
i = i + 5;
} while (i < 20);
fit@hcmus | Programming 1 | 2021 59
Counter-Controlled while Loops
o If you know exactly how many pieces of data need to be read, the
while loop becomes a counter-controlled loop.
fit@hcmus | Programming 1 | 2021 60
Sentinel-Controlled while Loops
o Sentinel variable is tested in the condition and loop ends when sentinel is
encountered.
o Example:
• Read some positive numbers and average them, but you do not have the preset
number of data items in mind. Suppose -999 marks the end of the data.
fit@hcmus | Programming 1 | 2021 61
Flag-Controlled while Loops
o A flag-controlled while loop uses a bool variable to control the loop.
o The flag-controlled while loop takes the form:
o Example: Number guessing game.
fit@hcmus | Programming 1 | 2021 62
Infinite Loop
o Example:
int x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
fit@hcmus | Programming 1 | 2021 63
Infinite Loop
o Example:
int x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
How to fix this loop?
fit@hcmus | Programming 1 | 2021 64
The Comma Operator
o Comma operator (,)
• evaluates a list of expressions
• returns the value of the last expression.
o Examples - What are the value of these variables after running:
• result = (first = 2, second = first + 1);
• result = (first = 2, second = first + 1, first =
second + 7);
• result = ((first = 2, second = first + 1), third =
second + 1);
fit@hcmus | Programming 1 | 2021 65
for Structure
fit@hcmus | Programming 1 | 2021 66
for Structure
o The general form of the for statement is:
for (Initialization_Action; Boolean_Expression; Update_Action)
Body_Statement
o The Initialization_Action, Boolean_Expression, and
Update_Action are called for loop control statements
• Initialization_Action usually initializes a variable (called the for loop control,
or for indexed, variable)
o In C++, for is a reserved word
fit@hcmus | Programming 1 | 2021 67
for Structure
Initialization_Action
Yes
Boolean_Expression Body_Statement Update_Action
No
for (Initialization_Action; Boolean_Expression; Update_Action)
Body_Statement
fit@hcmus | Programming 1 | 2021 68
Examples
o Example:
for (int i = 0; i < 10; i ++)
cout << i << " ";
cout << end;
fit@hcmus | Programming 1 | 2021 69
Examples
o Example:
int i = 0;
for ( ; i < 10; i ++)
cout << i << " ";
cout << end;
fit@hcmus | Programming 1 | 2021 70
Examples
o Example:
for (int i = 1; i <= 5; i++)
{
cout << "Hello !" << endl;
cout << "*" << endl;
}
o Example:
for (int i = 1; i <= 5; i++)
cout << "Hello !" << endl;
cout << "*" << endl;
fit@hcmus | Programming 1 | 2021 71
Examples
o Example:
for (int i = 1; i <= 5; i++);
cout << "Hello !" << endl;
o Example:
for ( ; ; )
cout << "Hello !" << endl;
fit@hcmus | Programming 1 | 2021 72
Examples
o Example:
for (int i = 10; i >= 0; i--)
cout << " " << i;
cout << endl;
o Example:
for (int i = 1; i <= 20; i = i+2)
cout << " " << i;
cout << endl;
fit@hcmus | Programming 1 | 2021 73
Choosing the Right Loop Structure
o All three loops have their place in C++
• If you know or can determine in advance the number of repetitions needed,
the for loop is the correct choice.
• If you do not know and cannot determine in advance the number of
repetitions needed, and it could be zero, use a while loop.
• If you do not know and cannot determine in advance the number of
repetitions needed, and it is at least one, use a do...while loop
fit@hcmus | Programming 1 | 2021 74
Nested Loops
o It is legal to nest one loop statement inside another loop statement.
o Example:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
fit@hcmus | Programming 1 | 2021 75
break and continue
fit@hcmus | Programming 1 | 2021 76
break and continue Statements
o break and continue alter the flow of control.
o break statement is used for two purposes:
• To exit early from a loop
• Can eliminate the use of certain (flag) variables
• To skip the remainder of the switch structure
o After the break statement executes, the program continues with
the first statement after the structure.
fit@hcmus | Programming 1 | 2021 77
break and continue Statements
o continue is used in while, for, and do…while structures.
o When executed in a loop
• It skips remaining statements and proceeds with the next iteration of the
loop
fit@hcmus | Programming 1 | 2021 78
Examples
fit@hcmus | Programming 1 | 2021 79
Examples
fit@hcmus | Programming 1 | 2021 80
Programming Example
fit@hcmus | Programming 1 | 2021 81
Checking Account Balance
o A local bank in your town needs a program to calculate a customer’s
checking account balance at the end of each month
o Data are stored in a file in the following form:
467343 23750.40
W 250.00
D 1200
W 75.00
I 120.74
fit@hcmus | Programming 1 | 2021 82
Checking Account Balance
o The first line of data shows the account number followed by the
account balance at the beginning of the month
o Thereafter each line has two entries:
• Transaction code
• Transaction amount
o Transaction codes
• W or w means withdrawal
• D or d means deposit
• I or i means interest paid by the bank
fit@hcmus | Programming 1 | 2021 83
Checking Account Balance
o Program updates balance after each transaction
o During the month, if at any time the balance goes below $1000.00,
a $25.00 service fee is charged.
fit@hcmus | Programming 1 | 2021 84
Checking Account Balance
o Program prints the following information:
• Account number
• Balance at the beginning of the month
• Balance at the end of the month
• Interest paid by the bank
• Total amount of deposit
• Number of deposits
• Total amount of withdrawal
• Number of withdrawals
• Service charge if any
fit@hcmus | Programming 1 | 2021 85
Checking Account Balance
o Input: file consisting of data in the previous format
o Output is of the following form:
Account Number: 467343
Beginning Balance: $23750.40
Ending Balance: $24611.49
Interest Paid: $366.24
Amount Deposited: $2230.50
Number of Deposits: 3
Amount Withdrawn: $1735.65
Number of Withdrawals: 6
fit@hcmus | Programming 1 | 2021 86
Questions and Answers
fit@hcmus | Programming 1 | 2021 87