FP - Topic 3 - Control Flows - Conditional and Loop
FP - Topic 3 - Control Flows - Conditional and Loop
Fundamentals of Programming
Control Flow
Rev.240901
HCM City 1
Content
• Conditional statements
if … else
switch … case
• Loops
• Exercises
2
Syntax of if statement
False
<Logic Exp>
True
Statement 1
Placed inside ( ), give result
(false = 0, true ≠ 0)
if (<Logic Expression>)
<Statement 1>; One statement or
Block of statements (must placed
between { and })
3
if statement
int main()
{
if (a == 0)
cout << “a is equal 0”;
if (a == 0)
{
cout << “a is equal 0”;
a = 2912;
}
}
4
Syntax of if …else statement
False
<Logic Exp> <Statment 2>
True
<Statement 1>
Placed inside ( ), give result
(false = 0, true ≠ 0)
if (<Logic Expression>)
<Statement 1>; Single Statment or
Block of statments (must placed
else between { and })
<Statement 2>;
5
if … else statement
int main()
{
if (a == 0)
cout << “a is equal 0”;
else
cout << “a is not equal 0”;
if (a == 0)
{
cout << “a is equal 0”;
a = 2912;
}
else
cout << “a is not equal 0”;
}
6
Notes
• The if statement can be nested inside another if
statement, and the else clause will be matched
with the nearest if clause within the same block.
if (a != 0)
if (b > 0)
cout << “a != 0 and b > 0”;
else
cout << “a != 0 and b <= 0”;
if (a !=0)
{
if (b > 0)
cout << “a != 0 and b > 0”;
else
cout << “a != 0 and b <= 0”;
} 8
Optimizing conditional logic with else
• When should we use else clause?
if (delta < 0)
cout << “No solution”;
if (delta == 0)
cout << “One solution”;
if (delta > 0)
cout << “Two solutions”;
if (delta < 0)
cout << “No solution”;
else // delta >= 0
if (delta == 0)
cout << “One solution”;
else
cout << “Two solutions”;
9
Exercises
• Write a C++ program that asks the user to input
a temperature and displays the corresponding
state based on the temperature value:
– If the temperature is below 0: print “Freezing”
– If the temperature is between 0 and 30: print “Cold”
– If the temperature is between 31 and 60: print
“Warm”
– If the temperature is above 60: print “Hot”
• Write two versions:
– First, without using else.
– Second, using else to optimize the code.
10
Notes
• Avoid semicolons (;) immediately after the if
clause
void main()
{
int a = 0;
if (a != 0)
cout << “a is not equal 0.”;
if (a != 0);
cout << “a is equal 0.”;
if (a != 0)
{
};
cout << “a is not equal 0.”;
}
11
Questions
• Identify the issues, explain the logic errors caused
by these mistakes, and rewrite the following
program to function correctly.
12
Syntax of switch statement
switch (<variable/expression>)
{
case <value1>:
<Var/Exp> True <S1>;
<Statement 1> break;
= <Value1>
case <value2>:
False <S2>;
break;
<Var/Exp> True
<Statement 2> …
= <Value2>
}
False
• <Variable/Expression> must
evaluate to a discrete value
(e.g., int, char).
• <Sx> : single statement or
block of statements.
13
The switch statement
int main()
{
int a;
cout << “Enter a: ”;
cin >> a;
switch (a)
{
case 1 : cout << “One”; break;
case 2 : cout << “Two”; break;
case 3 : cout << “Three”; break;
}
}
14
The switch…case statement
switch (<Var/Exp>)
<Var/Exp> Đ {
<Statement 1>
= <Value1> case <Value1>:<S1>;break;
S case <Value2>:<S2>;break;
Đ …
< Var/Exp >
<Statement 2> default:
= <Value2>
<Statement n>;
S
}
<Statement n>
15
The switch…case statement
int main()
{
int a;
cout << “Enter a: ”;
cin >> a;
switch (a)
{
case 1 : cout << “One”; break;
case 2 : cout << “Two”; break;
case 3 : cout << “Three”; break;
default : cout << “I don’t know”;
}
}
16
Notes
• The switch is single compound statement.
• The switch statement can be nested inside another
switch statement.
{
switch (a)
{
case 1 : cout << “One”; break;
case 2 : switch (b)
{
case 1 : cout << “A”; break;
case 2 : cout << “B”; break;
} break;
case 3 : cout << “Three”; break;
default : cout << “I don’t know”;
}
}
17
Each case in a switch statement must have a distinct value. If multiple case statements have the same value, the compiler will throw an error. This ensures that the program knows exactly which block of code to execute for each specific value.
Notes
• The values in each case must be unique.
switch (a)
{
case 1 : cout << “One”; break;
case 1 : cout << “ONE”; break;
case 2 : cout << “Two”; break;
case 3 : cout << “Three”; break;
case 1 : cout << “1”; break;
case 1 : cout << “One”; break;
default : cout << “I don’t know”;
}
18
Notes
• The switch statement jumps to the matching case
and executes code until it encounters a break
statement or reaches the end of the switch block.
switch (a)
{
case 1 : cout << “One”; break;
case 2 : cout << “Two”; break;
case 3 : cout << “Three”; break;
}
19
Notes
• In some cases, omitting the break statement
can be advantageous.
switch (a)
{
case 1 : cout << “Odd”; break;
case 2 : cout << “Even”; break;
case 3 : cout << “Odd); break;
case 4 : cout << “Even”; break;
}
switch (a)
{
case 1 :
case 3 : cout << “Odd”; break;
case 2 :
case 4 : cout << “Even”; break;
}
21
Question
• What is the output when the input is 2?
• How would you modify the program if you only want a
single message for each case?
22
Some experiences
vif statement vswitch statement
if (a == 1) switch (a)
cout << “One”; {
if (a == 2) case 1: cout <<“One”;
cout << “Two”; break;
if (a == 3) case 2: cout << “Two”;
cout << “Three”; break;
if (a == 4) case 3: cout << “Three”;
cout <<“Four”; break;
if (a == 5) case 4: cout << “Four”;
cout <<“Five”; break;
case 5: cout << “Five”;
}
23
Some experiences
vswitch statement v if statement
24
Questions
• Examine the following code and identify the
logical error. How would you fix it to function
correctly?
25
Questions
• Predict the output for the input value 3. Then,
modify the code to ensure only one case is
executed for any valid input.
26
Questions
• Analyze the code carefully and answer the questions
below.
• Identify any logical mistakes, and suggest how to improve
the code to avoid potential pitfalls.
27
Questions
• Writing a C++ program to check a person's
eligibility for a job based on several
conditions:
– The person must be at least 18 years old.
– The person must either have a college degree
or have at least 5 years of work experience.
– The person must not have a criminal record.
28
Questions
• The following code attempts to check these
conditions, but there is a logical mistake that
causes incorrect results.
– Analyze the code, explain the error, and rewrite the code
correctly using parentheses to fix the logic.
29
Content
• Conditional statements
• Loops
for …
while…
do …while
• Exercises
30
Problem
• Example
– Write the program to print out all integer numbers in
range 1 to 10
=> Solution: Use 10 cout statement
– Write the program to print out all integer numbers in
range 1 to 1000
=> Solution: Use 1000 cout statement. Wow!
• Better solution
– Use loop statements to repeat an action while the
specific condition is still valid.
– C/C++ supports 3 loop syntaxs: for, while, do…
while
31
Syntax of for statement
<Initialization>
<Step>
<Loop True
<Statement>
Condition>
False
void main()
{
int i;
for (i = 0; i < 10; i++)
cout << i;
33
Nest
• for statement is single statement and can be
nested in others.
34
Flexible components of a for loop
• Inside a for statement, the <initialization>
part can be omitted.
int i;
for (i = 0; i < 10; i++)
cout << i; <Initialization>
int i = 0; <Step>
for (; i < 10; i++)
cout << i; <Loop True
Condition> <Statement>
False
35
Flexible components of a for loop
• Inside a for statement, the <step> part can
be omitted.
int i;
for (i = 0; i < 10; i++)
cout << i; <Initialization>
36
Flexible components of a for loop
• Inside a for statement, the <loop condition>
part can be omitted.
int i;
for (i = 0; i < 10; i++)
cout << i;
for (i = 0; ; i++)
cout << i;
for (i = 0; ; i++)
{
if (i >= 10)
break;
cout << i;
}
37
Using break and continue in loops
• The break statement will terminate the loop
immediately.
• The continue statement will skip the current iteration
and move to the next iteration of the loop.
for (i = 0; i < 10; i++)
{
if (i % 2 == 0)
break;
cout << i;
}
39
Question
• Analyze the following code and predict the output.
40
Question
• Analyze the following code and answer the
questions below.
41
Notes
• Don't add a semicolon (;) immediately after
the for statement.
42
Notes
• In a for loop, the <Initialization>, <Loop
Condition>, and <Step> are separated by
semicolons (;).
• If there are multiple statements in these parts,
each statement is separated by commas (,).
43
Question
• Analyze the code and predict the output of the program.
• Modify the loop so that it includes an additional condition:
stop the loop if k becomes negative. Predict the output of
the program after change.
44
Syntax of while statement
<Loop True
<Statement>
Condtion>
False
Expression will return 0 (false)
or != 0 (true)
while (<Loop Condition>)
<Statement>;
Single statement or
Block of statements
(place between { and })
45
Example
int i = 0;
while (i < 10)
{
cout << i;
i++;
}
int i = 0;
for (; i < 10; )
{
cout << i;
i++;
}
46
Nested
• A while loop can be nested inside other loops or
conditional statements, such as if, for, or even
another while.
if (n < 10 && m < 20)
{
while (n >= 1)
{
while (m >= 1)
{
cout << m;
m--;
}
n--;
}
}
47
Pre-Test Behavior
• The while statement may not execute at all if the
loop condition evaluates to false on the first check.
void main()
{
int n = 1;
while (n > 10)
{
cout << n;
n--;
}
…
}
48
Notes
• Don't add a semicolon (;) immediately after the
while statement.
int n = 0;
while (n < 10);
{
cout << n;
n++;
}
n = 1;
while (n < 10)
cout << n;
}
50
Question
• Analyze the following program:
51
Syntax of do… while statement
<statement>
<Loop True
condition>
False Single statement or
Block of statements
do (place inside { })
<Lệnh>;
while (<Đ/K lặp>);
Expression will return 0 (false)
or != 0 (true)
52
Example
int i = 0;
do
{
cout << i;
i++;
}
while (i < 10);
int i = 0;
cout << i;
i++;
for (; i < 10; )
{
cout << i;
i++;
}
53
Notes
• do … while statement might not loop because
loop condition return false at the first time.
void main()
{
int n;
do
{
cout << “Enter n: ”;
cin >> n;
}
while (n < 1 || n > 100);
}
55
Notes
• do … while statement may be looped infinite.
…
int n = 1;
do
{
cout >> n;
n--;
}
while (n < 10);
n = 1;
do
cout >> n;
while (n < 10);
…
56
for, while, do… while
• Are they similar? When to use?
int n = 10;
for (int i = 1; i <= n; i++)
cout << i;
int i = 1;
while (i <= n)
{
cout << i; i++;
}
int i = 1;
do {
cout << i; i++;
} while (i < n);
57
Questions
• Write a program to calculate the factorial of a
number entered by the user.
– The user must be prompted to enter a non-
negative integer repeatedly until they provide a
valid input.
58
Questions
• Write a program based on requirements:
– A game asks the player to guess a randomly
generated number between 1 and 100.
§ The player should be prompted to guess the number
until they get it right.
§ After each guess, the program will give feedback on
whether the guess is too high or too low.
§ The guessing prompt should appear at least once.
59
Content
• Conditional statements
• Loops
• Exercises
67
Exercises
Write C/C++ program to classify a triangle:
- Enter 3 positive real numbers a, b, c (re-enter if
invalid).
- Check if a, b, c can forms a triangle.
- If yes, print the triangle type.
(normal, right, isosceles, right-isosceles, equilateral).
Input format:
Enter 3 positive real numbers = 3 4 5
Output format (can form a triangle):
Can form a triangle.
Right triangle.
Output format (cannot form a triangle):
Cannot form a triangle!
68
Exercises
Write C/C++ program to compute electricity bill:
- Enter old and new kWh (re-enter if invalid).
- Compute the price and print result.
Price table:
Levels Consumed kWh Unit prices
1 0 – 100 1549 đ
2 101 – 150 1600 đ
3 151 – 200 1858 đ
4 201 – 300 2340 đ
5 301 – 400 2615 đ
6 401 – more 2701 đ
69
Exercises
Write C/C++ program find max and min as follow:
- Enter a sequence of positive integers.
(re-enter if invalid, stop if enter zero).
- Print max and min (do not include zero).
Notes: do not use array.
Input format:
Number 1 = 5
Number 2 = 3
Number 3 = 9
Number 4 = 0
Output format:
Max = 9
Min = 3
70
Exercises
Write C/C++ program to find prime numbers:
- Enter a positive integer N (re-enter if invalid).
- Print all prime numbers <= N.
Input format:
Enter a positive integer = 11
Output format:
#1 = 2
#2 = 3
#3 = 5
#4 = 7
#5 = 11
There are 5 prime numbers.
71
Exercises
Write C/C++ program to find GCD (greatest common
divisor) and LCM (least common multiple):
- Enter 2 positive integers a, b (re-enter if invalid).
- Print:
- GCD of a, b.
- LCM of a, b.
Input format:
Enter 2 positive integers = 8 12
Output format:
GCD = 4
LCM = 24
72
Exercises
Write C/C++ program to print bit
representation of an integer:
- Enter integer N and positive integer M.
- Print the first M bit from the right of N.
Input format:
Enter N, M = 11 3
Output format:
The first 3 bit from the right of 11: 011
73
Exercises
Write C/C++ program to read phone number as
follow:
- Enter a phone number (10 digits max) (re-enter
if invalid).
- Print how to read the phone number.
Notes:
- Do not use array/string processing (get
element, get length).
Input format:
Phone number: 838272727.
Output format:
Eight three eight two seven two seven two seven
74
Exercises
Write C/C++ program as follow:
- Enter a positive integer N (re-enter if
invalid).
- Check if:
a) Digits of N is in descending order
from the ones.
b) Digits of N is symmetric.
Input format:
Enter N = 12344321
Output format:
Not descending.
75
Exercises
Write C/C++ program to count the number of
days in a month:
- Enter month and year.
- Count the number of days in the month
and print result.
Input format:
Enter month and year = 6 2012
Output format:
Month 6 in year 2012 has 30 days.
76
Exercises
Write C/C++ program as follow:
- Enter a positive integer N.
- Compute and print results:
a) N! = 1 * 2 * … * N.
b) ln(2) = 1 - 1/2 + 1/3 - … +/- 1/N.
c) PI = 4 ( 1 – 1/3 + 1/5 – … +/- 1/(2*N + 1) ).
d) S = a1 + a2 + … ak ( { ai } are all square
numbers <= N).
Output format:
N! = <a result>
ln(2) = <b result>
PI = <c result>
S = <d result>
77
Exercises
Write C/C++ game for grade 1 student to practice +, - as follow:
- Computer asks randomly + or – between two positive
integers.
- Player answers the result (re-enter if wrong).
- Computer continues to asks until player answers zero.
- Constraint: operands, result in range [1..99].
Notes: use srand, rand (<stdlib.h>) to generate random
numbers.
Game format:
Question 1: 2 + 5 = ?
Answer: 7
Question 2: 18 – 9 = ?
Answer: 8
Answer: 9
Question 3: 6 + 25 = ?
Answer: 0
78
Exercies
Write C/C++ program to find all numbers
satisfying:
- A 3-digit positive integer.
- Tens digit = Hundreds digit + Ones digit.
Output format:
1: <the 1st satisfied number>
2: <the 2nd satisfied number>
…
N: <the Nth satisfied number>
There are N satisfied numbers.
79
Exercises
Write C/C++ program to print month calendar as follow:
- Enter month and year (re-enter if invalid).
- Enter day of week of the first day in the month (for
alignment).
- Print the calendar of the month.
Input format:
What month and year to view calendar? 9 2022
What is the day of week of the first day? 5
Output format:
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
80
The End