Chapter 3
Chapter 3
Control Structures
By AsnakY.
Program Control Constructs
⚫ Program Control Structures
⚫ Selection statements
⚫ if Statement
⚫ switch statement
⚫ Repetition statements
⚫ while statement
⚫ for statement
⚫ Do....while statement
⚫ Recommendations cautions
⚫ Loop Control Statements
⚫ Labeled Statements
⚫ Goto, Continue and Break
2 statements
Program Control Constructs
⚫ A running program spends all of its time executing instructions
or statements in that program.
⚫ The order in which statements in a program are executed is
called
flow of that program.
⚫ Programmers can control which instruction to be executed
in a program, which is called flow control
⚫ There are three basic types of program flows/ flow control
⚫ Sequential - statements in a program are executed one after the other
in sequence.
⚫ Selection(Branching) - executes part of the code based on the
condition.
⚫ Iteration(Looping) - statements inside looping statement are
3
executed repeatedly as long as a condition is true
Sequential structure
• In C++, a sequential structure refers to a programming
construct where statements are executed in a linear order, one
after the other.
• This is the most basic type of control flow in programming.
• In a sequential structure, the program starts from the first
statement and proceeds to the last statement, executing each
line in turn.
• Example:
#include <iostream>
int main() {
int a = 5; // Step 1: Declare and initialize variable a
int b = 10; // Step 2: Declare and initialize variable b
int sum = a + b; // Step 3: Calculate the sum of a and b
cout << "The sum is: " << sum << endl; // Step 4: Output
the result
return 0; // Step 5: Exit the program}
Selection/conditional Statement
⚫ Selection statements are statements in a program where there
are points at which the program will decide at runtime
whether some part of the code should or should not be
executed.
⚫ There are two types of selection statements in C++
⚫ if statement
⚫ switch statement
⚫ The different forms of the “if ” statement are:
⚫ The simple if Statement
⚫ The if…else Statement
⚫ The if …else if Statement
5
The simple if statement
⚫ The simple if statement will decide only one part of the
program to be executed if the condition is satisfied or
ignored if the condition fails.
statements;
5 Flow
Diagram
The Simple if Statements….
⚫ Thus, expression can
be:
Relational expression,
A variable,
A literal constant, or
Assignment operation, as the final result is whatever we have at the
right hand side and the one at the left hand side is a variable.
Example - 1
#include<iostream>
using namespace std;
void main ()
{ int a =
10;
if( a < 20 ){
cout
7 <<
"a is
The Simple if Statements ….
⚫ Adding a semicolon at the end of an if clause is a
common mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
cout<<“The area the circle is“<<area;
}
⚫If there is only one statement that has to be executed after
if, the opening and closing curly bracket can be removed
if( a < 20 )
cout << "a is less than 20;" <<
endl;
8
The if...else Statement
⚫ These selection statement is used if there are exactly
two selections
⚫ Syntax:
if (Expression)
{
if-statement(s);
}
else
{
else-statement(s);
}
8 Flow
Diagram
The if...else Statement, example
1. Write a program that reads a number and then
determine whether it is odd or even.
Answer
#include<iostream>
using namespace std;
void main (){
int num;
cout<<"En
ter a
number \
n";
cin>>num;
if( num%2
= = 0){
c
o
u
10 t
<
Nesting if statements within another if statement
⚫ One or more if statements can be nested with in another if
⚫ The nesting will be used to test multiple conditions to perform a
task.
⚫ It is always recommended to indent nested if statements to enhance
readability of a program.
⚫ The General Syntax might be:
if(expression1) els
{ e
if(expressio { if(expressio
n2) n3)
statemen statement
tN; R;
else }else
statementM; statementT
11 } ;
Nesting if statements ….., example
Write a program that reads three numbers and then find the largest
one.
#include<iostream.h
> void main (){
int a, b, c;
cout<<"Enter a number \
n"; cin>>a>>b>>c;
if( a>b){
if(a>c)
cout<<a<<" is the maximum
"<<endl; else
cout<<c<<" is the maximum
"<<endl;
}
else{
if(b>c)
cout<<b<<" is the maximum
"<<endl;
12 else
cout<<c<<" is the maximum
If……else if Statement
⚫ if…else if statement is important if there are
more than two conditions.
⚫ Syntax:
if(Expression1)
{
statement(s);
}
else if(Expression2)
{
statement(s);
}
.
.
else
{
statement(s);
1 }
2
Example : The following code snippet depicts how nested if else statement is used to determine the grade based on a score
input
#include <iostream>
using namespace std;
int main() {
// Declare a variable to hold the score
float score; // Prompt user for input
cout << "Enter your score: ";
cin >> score; // Determine the grade using if...else if statements
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else if (score >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F" << endl; }
return 0;}
14
Trace if-else statement
15
Trace if-else statement…
16
Trace if-else statement…
Suppose score is 70.0 The condition is
true
17
Trace if-else statement
Suppose score is
70.0
if (score > = 90.0)
cout<<“grade = grade is
A”; C
else if (score > =
80.0)
cout<<“grade
cout<<“grade==C'';
elseB”;if (score > = 60.0)
elsecout<<“grade
if(score > = 70.0)
= D”;
else cout<<“grade =
F”;
18
Trace if-else statement
Suppose score is
70.0
if (score > = 90.0)
cout<<“grade =
A”; else if (score > =
80.0) cout<<“grade
= B”; else if (score
> = 70.0) Exit the if
cout<<“grade = C”; statement
else if (score > =
60.0) cout<<“grade
= C”;
else
cout<<“grade =
F”;
19
Multiple Alternative if Statements
20
Note…..
What is the difference between program A and B?
A B
#include<iostream> #include<iostream>
using namespace std; using namespace std;
void main(){ void main(){
int a; int a;
cout<<"Enter a\ cout<<"Enter a\
n"; cin>>a; n"; cin>>a;
if(a>0) if(a>0)
cout<<a<<" is cout<<a<<" is
positive\n"; positive\n";
else if(a<0) if(a<0)
cout<<a<<" is Negative\ cout<<a<<" is Negative\
n"; else n"; if(a==0)
cout<<a<<" is zero\n"; cout<<a<<" is zero\n";
21} }
Switch Statements
⚫ The if/else construct can become hard to work when
managing multiple options with numerous choices. The
switch statement offers a more efficient way to select
from a set of alternatives based on the value of an
expression.
⚫ The switch statement has four components:
switch
case
default
break
⚫ Where default and break are Optional
22
Switch Statements, Syntax
switch (expression) {
case constant1:
// Code block for case 1
break;
case constant2:
// Code block for case 2
break;
case constant3:
// Code block for case 3
break;
// You can have as many cases as needed
default:
// Code block if no case matches
}
23
Switch Statements, Flow Chart
24
Switch Statements…
⚫ The out put of “expression” should always be a constant value.
⚫ The value1, ..., and value N must have the same data type as the
value of the expression.
⚫ First expression is evaluated, and the outcome, will compared to each
of the numeric constants in the case labels, in the order they appear,
until a match is found.
⚫ The statements following the matching case are then executed.
⚫ Each case may be followed by zero or more statements (not just
one statement).
⚫ When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement.
⚫ Not every case needs to contain a break. If no break appears, the
flow of control will fall through to subsequent cases until a break is
25 reached.
Switch Statements…
⚫ The final default case is optional and is executed if none of
the earlier cases provide a match.
⚫ that is if the value of the “expression ” is not equal to any of the
case
labels, then the statements under default
switchwill
(N){be executed.
switch (N){
case 1:
case 1: x=10;
break;
case 2:
x=10; x=2
case 2: 0;
break;
case 3:
x=20; x=3
case 3: 0;
bre
ak;
26
x=30; }
Switch Statements, Example
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
2
8
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl; }
return 0;
}
Switch vs. if …else if
Statements
switch (expression)
{ case val1: if (expression ==
stateme val1)
nt statement
break;
case val2: else if
statement (expression==val2)
break;
…. statement
case ….
valn: statemen else if (expression==
t valn)
default break; statement
: statemen
t break; else
2 } statement
9
Repetition Statement
⚫ There may be a situation when you need to execute a block
of code several number of times.
⚫ Repetition statements control a block of code to be executed
repeatedly
⚫ for a fixed number of times or
⚫ until a certain condition fails.
⚫ There are three C++ repetition statements:
⚫ The While statement or loop
⚫The For Statement or loop
⚫ The do…while statement or loop
30
The while statement
⚫ The while statement (also called while loop) provides a
way of repeating a statement or a block as long as a
condition holds / is true.
⚫ The general form
of the while loop
is:
while(conditi
on)
{
statements;
}
31
The while statement
⚫ How while works
⚫ First the condition is evaluated.
⚫ If the outcome is non zero then statement(s) (called the loop body)
is executed and the whole process is repeated.
⚫ Otherwise, the loop is terminated.
⚫ Example // C++ program to illustrate while loop
#include <iostream>
using namespace std;
int main() {
// initialization expression
int i = 1;
// test expression
while (i < 6) {
cout << "Hello World\n";
// update expression
i++; }
32 return 0; }
The while statement, Example
Write a program that reads and calculates the sum of an
unspecified number of integers.The input 0 signifies the end of
the input.
#include <iostream>
using namespace std;
void main (){
int n = 1, sum =
0; while(n!=0){
cout< <"Enter a number \
n"; cin>>n;
sum=sum+n;
}
cout<<"\ n Sum is
33 "< <sum< <endl;
The for statement
Syntax
A for loop is a
repetition control
structure that
allows you to
efficiently write a
loop that needs to
execute a specific
number of times.
Flow
Chart
34
The for statement …
Here is the flow of control in a for loop:
35
The for statement …
⚫ Even though it is not recommended, init, condition
and increment can be optional or can be ignored.
⚫ This means that they can take NULL statement.
⚫ While making one or more of the three expressions null,
the semi colons CAN NOT be ignored.
⚫ Example:
⚫ for(;n<10;)
⚫ for(;n<10;n++)
⚫ for( ; ; ) //is an infinite loop unless an otherwise there is if
statement inside the loop.
⚫ init and increment can be one or more statements.
⚫ The composite statements should be separated by a
3
comma.
6 ⚫ E.g. for(n=0,i=100; n!=i; n++,i--) {…}
The for statement, example
#include <iostream>
using namespace std;
int main () {
for( int a = 10; a < 20; a = a + 1 )
{ cout << "value of a: " << a <<
endl;
}
return 0;
}
#include<iostream>
using namespace std;
void main()
{ for(int
i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
cout<<"*“<<“ “;
cout<<“\n”;
39 }
The for vs. while statements
⚫ The difference between for loop and while loop
primarily lies in their structure, typical use cases, and
when they are most appropriately used.
⚫ For example : print numbers from 1 to 5.
int i = 1;
for (int i = 1; i <= 5; i+
while (i <= 5) {
+) {
cout << i << endl;
cout << i << endl;
i++; }
}
40
The do…while statement
⚫ The do-while loop is similar to the while loop, but the condition is
checked after the code block is executed. This makes it a post-test
loop, meaning the loop will always execute at least once, even if the
condition is false from the beginning.
⚫ The general form
is: do
{
statement;
}
while(expression);
Flow
Chart
41
The do…while statement…
⚫ How it works
⚫ First statement is executed and then expression is evaluated.
⚫ If the outcome of the expression is nonzero, then the whole process
is repeated.
⚫ Otherwise the loop is terminated.
⚫ The while loop and for loop are called pre-test
loops
⚫ because the continuation condition is checked before the loop
body is executed.
⚫ The do-while loop is called a post-test loop
⚫ because the condition is checked after the loop body is
executed.
42
The do…while statement, Example
Write a program that reads and calculates the sum of an unspecified
number of integers.The input 0 signifies the end of the input.
#include <iostream>
using namespace std;
void main (){
int n = 1, sum =
0; do{
cout< <"Enter a number \
n"; cin>>n;
sum=sum+n;
}while(n!=0);
cout<<"\ n Sum is
43
"< <sum< <endl;
Types of loops
⚫ Count controlled loops
⚫ Types of where the number of iterations is controlled by a counter.
⚫ Count-controlled loops contain:
⚫ Initialization: Sets the initial value of the counter.
⚫ Condition: Checked before each iteration; if false, the loop ends
⚫ Increment/Decrement: Updates the counter after each iteration.
⚫ Event-controlled loops
⚫Repeat a statement or block until a condition within the loop
body changes that causes the repetition to stop.
44
Types of Loops…
⚫ Types of Event-Controlled Loops
⚫ Sentinel controlled:
⚫ Theloop terminates when a specific "sentinel" value is
encountered.
⚫End-of-file controlled:
⚫ Keep processing data as long as there is more data in the file
⚫ Flag controlled:
⚫ Keepprocessing data until the value of a flag changes in the
loop body
⚫Which type of loop is appropriate for the following exercise?
47
The Labeled Statements
⚫
In C++, labeled statements allow you to mark a
specific part of code with a label, which can be useful
in combination with control flow statements.
⚫ There are three types of labeled statements.
identifier : statement
case constant-expression : statement
default : statement
⚫ All use a colon to separate some type of label
from the statement.
⚫ The case and default labels are specific to case (or switch)
statements
⚫ 48
Identifiers used as labels can’t be used anywhere in the
The goto statement
⚫ A goto statement provides an unconditional jump from the
goto to a labeled statement in the same function.
⚫NOTE:
⚫ Use of goto statement is highly discouraged because it makes
difficult to trace the control flow of a program, making the program
hard to understand and hard to modify.
⚫ Any program that uses a goto can be rewritten so that it doesn't
need
the goto.
⚫ Syntax:
⚫ The syntax of a goto statement in C++ is:
goto label;
.. .
49 label: statement;
The goto statement …
⚫ Where label is an identifier that identifies a labeled statement. A
labeled statement is any statement that is preceded by an identifier
colon by aExample #include < iostream>
followed
(:). Using name space std;
void main (){
int a = 10;
LOOP:do{ / / do loop execution if( a = =
15){
a = a + 1;
goto LOOP; / / skip the iteration.
}
cout < < "value of a: " < < a < < endl; a = a + 1;
}while( a < 20 );
}
Flow
50 chart
Example :print hello Ethiopia using goto
#include <iostream>
using namespace std;
int main() {
int count = 1; // Initialize a counter
start: // This is the label
cout << "Hello Ethiopia!" << endl;
count++; // Increment the counter
if (count <= 5) { // Condition to repeat the message 5 times
goto start; // Jump to the label 'start'
}
return 0;} Hello Ethiopia!
Hello Ethiopia!
Hello Ethiopia!
Hello Ethiopia!
Hello Ethiopia!
Continue statement
⚫ The Continue statement works different loop.
⚫ In a for loop: The continue statement skips the rest of the code inside the
loop for the current iteration
⚫ It then moves directly to the increment expression and checks the condition
again.
⚫ Example:
for(int n=10;n>0;n--)
{
if(n==5)
continue; //causes a jump to n—
cout<<n<< “,”;
}
5
1
The continue statements
⚫ When the continue statement appears inside nested loops, it applies to
the loop immediately enclosing it, and not to the outer loops.
⚫ Example:
while(more)
{ The continue statement applies
for(i=0;i<n;i++) to the “for” loop, and not to
{ the “while” loop.
cin>>num;
if(num<0)
outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
continue outer;
}
}
54
The break statement
⚫ A break statement may appear inside a loop (while,
do...while, or for) or a switch statement.
⚫ It causes a jump out of these constructs, and hence terminates them.
⚫ Like the continue statement, a break statement only applies to
the “loop” or “switch” immediately enclosing it.
⚫ It is an error to use the break statement outside a loop or a switch
statement.
⚫ Example
for(n=10;n>0;n--){
cout<<n<< “,”;
if(n = = 3){
cout<< “count
down
aborted!!”;
55 break;
}
The break statement
#include<iostream>
Example Using name space std
int main ()
Write a c++ program {
that prints prime for (int i=2; i<100; i++)
{
numbers less than 100. bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
56
}
Statement Labels and Breaking with Labels
outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
break outer;
}
}
57
Exercises
1. Write for, do-while, and while statements to compute the following
sums and products.
⚫ 1+2+3+…+100
⚫ 5+10+15+…+50
⚫ 1+1/2+1/3+1/4+…1/15
⚫ 1*2*3*…*20
2. Write an application to print out the numbers 10 through 49 in the
following manner
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
3. Write a C++ program that accepts a positive number from the
user and displays the factorial of that number. Use for loops to
find the factorial of the number.
58
Exercises…
4. Write a weather-calculator program that asks for a list of the
previous 10 days’ temperatures, computes the average, and
prints the results. Use a while loop for the 10 repetitions.
5. Write a C++ code that computes the sum of the following
series. Sum = 1! + 2! + 3! + 4! + …n! . The program should
accept the number from the user.
6. Write c++ programs that gives the following outputs
59
Exercises
⚫ An integer number is said to be a perfect number if its factors,
including 1 (but not the number itself), sum to the number. For
example, 6 is a perfect number, because 6 = 1 + 2 + 3.Write a
method perfect that determines whether parameter number is a
perfect number. Use this method in an application that determines
and displays all the perfect numbers between 1 and 1000.
⚫ The greatest common divisor (GCD) of two integers is the largest
integer that evenly divides each of the two numbers.Write a
method gcd that returns the greatest common divisor of two
integers.
60
Assignment 2
1. Write a C++ program that counts the number of digits in
an integer number. For example; 23,498 has five digits.
2. Write a C++ application that can compute the letter grade
of a student after accepting the student’s mid and final mark.
The program should only accept mid result [0-40] and final
[0- 60].
If the data entered violates this rule, the program should
display that the user should enter the mark in the specified
range.
The program is also expected to run until the user
refuses to continue.
3. Write a C++ program that counts the number of digits
61
in an integer number. For example; 23,498 has five
digits.
Assignment
2…
3. Write a c+ + program that prints the shape shown on
the right side of this slide
4. Develop a calculator program that computes and
displays the result of a single requested operation.
⚫ Example:
⚫ If the input is 15 * 20, then the program should display 15 *
20
equals 300
⚫ If the operator is not legal, as in 24 ~ 25 then the program
displays
~ is unrecognized operator
⚫ As a final example, if the denominator for a division is 0, as in
the following input: 23 / 0, then the program should display
the following: 23 / 0 can’t be computed: denominator is 0.
continue
⚫ .The program is also expected to run until the user refuses to
62
Assignment 2…
5. Write c++ programs that gives the following
outputs.