Chapter 3
Chapter 3
Control Structures
ByAsnakY.
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 statements
2
Program Control Constructs
⚫ Arunning 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 executed
repeatedly as long as a condition is true
3
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 aprogram 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.
5 Flow Diagram
The Simple if Statements….
⚫ Thus, expression can be:
Relational expression,
Avariable,
Aliteral 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 << "a is less than 20;" << endl;
}
cout < < "value of a is : " << a < < endl;
7 }
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<<"Enter a number \ n";
cin>>num;
if( num%2 = = 0){
cout <<num<<" is even" < < endl;
}
else{
cout < < num<<" is odd " < < endl;
}
}
10
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) else
{ {
if(expression2) if(expression3)
statementN; statementR;
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;
else
cout<<c<<" is the maximum "<<endl;
}
}
12
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);
12 }
Example : Thefollowingcode snippet depictshownestedifelse statement isusedto 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…
17
Trace if-else statement
18
Trace if-else statement
Suppose score is 70.0
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 cout<<"Enter
a\n"; cin>>a; a\n"; cin>>a;
if(a>0) if(a>0)
cout<<a<<" is positive\n"; cout<<a<<" is positive\n";
else if(a<0) if(a<0)
cout<<a<<" is cout<<a<<" is
Negative\n"; else Negative\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 alwaysbea 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 reached.
25
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 will be executed.
switch (N){ switch (N){
case 1:
case 1: x=10;
x=10; break;
case 2:
case 2: x=20;
x=20; break;
case 3: case 3:
x=30;
x=30; break;
} }
Even if N is 1 or 2, x will have 30 x will have either 10, 20, 30
based on the value of N.
26
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;
28
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 == val1)
statement statement
break;
else if (expression==val2)
case val2:
statement statement
break;
…. ….
case valn:
statement else if (expression== valn)
break; statement
default:
statement else
break; statement
29 }
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 astatement or a block aslong asacondition
holds / is true.
⚫ The general form of
the while loop is:
while(condition)
{
statements;
}
31
The while statement
⚫ How while works
⚫ First the condition is evaluated.
⚫ If the outcome is non zero then statement(s) (calledthe loopbody)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 "< <sum< <endl;
33 }
The for statement
Syntax
Afor 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 …
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is
executed and the loop gets back to step 2.
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 CANNOTbe 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 comma.
⚫ E.g. for(n=0,i=100; n!=i; n++,i--) {…}
36
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;
}
38
Nested Loop
⚫ Any loop can be nested inside of another loop.
⚫ C++ allows at least 256 levels of nesting.
⚫ Example;Write a program that uses nested loops to print the
following output.
#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 "< <sum< <endl;
43
}
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:
⚫ Keep processing data until a special value that is not a possible data
value is entered to indicate that processing should stop.
⚫End-of-file controlled:
⚫ Keep processing data as long as there is more data in the file
⚫ Flagcontrolled:
⚫ Keep processing data until the value of a flag changes in the loop
body
⚫Which type of loop is appropriate for the following exercise?
Write a program that reads and calculates the sum of an unspecified number
of integers. The input 0 signifies the end of the input.
45
Recommendations
⚫ Use the one that is most intuitive and comfortable for you.
⚫ In general, a for loop may be used if the number of repetitions
is known, as, for example, when you need to print a message
100 times.
⚫ Awhile loop may be used if the number of repetitions is not
known, as in the case of reading the numbers until the input is
0.
⚫ Ado-while loop can be used to replace a while loop if the
loop body has to be executed before testing the continuation
condition.
46
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
caseconstant-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
⚫ Identifiers used as labels can’t be used anywhere in the program
47
The goto statement
⚫ Agoto 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 aprogram, 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;
.. .
label:statement;
48
The goto statement …
⚫ Where label is an identifier that identifies a labeled statement.Alabeled
statement is any statement that is preceded by an identifier followed by a
colon (:). Example
#include < iostream>
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 chart
49
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<< “,”;
}
51
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 to
for(i=0;i<n;i++) 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;
}
}
52
The break statement
⚫ A break statement may appear inside a loop (while, do, or for) or a
switch statement.
⚫ It causes a jump out of these constructs, and hence terminates them.
⚫ Like the continue statement, abreak 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!!”;
break;
}
}
53
The break statement
#include<iostream>
Example Using name space std
int main ()
Write a c++ program that {
prints prime numbers less for (int i=2; i<100; i++)
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;
54
}
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;
}
}
55
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 aC++ 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.
56
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
57
Exercises
⚫ Aninteger number is said to be aperfect 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.
58
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 in
an integer number. For example; 23,498 has five digits.
59
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 becomputed:denominator is 0.
⚫ The program is also expected to run until the user refuses to
continue.
60
Assignment 2…
5. Write c++ programs that gives the following outputs.