Chapter 3 Control Structures
Chapter 3 Control Structures
Control Structures
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
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 executed
repeatedly as long as a condition is true
3
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.
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;
int main (){
int a = 10;
if( a < 20 ){
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
6
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;
7
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;
int 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;
}
return 0;
}
9
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:
else
if(expression1)
{
{
if(expression3)
if(expression2)
statementR;
statementN;
else
else
statementT ;
statementM;
}
}
10
Nesting if statements ….., example
▪ Write a program that reads three numbers and then find the largest one.
#include<iostream>
using namesspace std;
int 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;
}return 0;
11 }
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
if …else if Statement, example
▪ The following code snippet depicts how nested if else
statement is used to calculate letter grade from a score out
of 100.
if(score >= 90)
cout<< “\n your grade is A”;
else if (score>=80)
cout<< “\n your grade is B”;
else if (score>=70)
cout<< “\n your grade is C”;
else if (score>=60)
cout<< “\n your grade is D”;
else
cout<< “\n your grade is F”;
13
Trace if-else statement
14
Trace if-else statement…
15
Trace if-else statement…
Suppose score is 70.0 The condition is true
16
Trace if-else statement
17
Trace if-else statement
Suppose score is 70.0
18
Multiple Alternative if Statements
19
Note…..
▪ The else clause matches the most recent if clause in the same
block.
20
Note…..
▪ Nothing is printed from the preceding statement.
▪To force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1, j = 2, k = 3;
if (i > j) {
if (i > k)
cout<<“A";
}
else
cout<<“B”;
This statement prints B.
21
Note…..
What is the difference between program A and B?
A B
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main(){ int main(){
int a; int a;
cout<<"Enter a\n"; cout<<"Enter a\n";
cin>>a; 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 Negative\n"; cout<<a<<" is Negative\n";
else if(a==0)
cout<<a<<" is zero\n"; cout<<a<<" is zero\n";
return 0; return 0;
22 } }
Switch Statements
The if/else construct can be cumbersome when you have to
deal with multiple selections with many alternatives
The switch statement provides a way of choosing between 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
23
Switch Statements, Syntax
switch (expression) {
case value1:
statement(s)1;
break;
case value2:
statement(s)2;
break;
………
case valueN:
statement(s)N;
break;
default:
statement(s)-for-default;
}
24
Switch Statements, Flow Chart
25
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 reached.
26
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.
27
Switch Statements, Example
Write a java program that converts students score to letter
grade using switch statement
int Choice = score/10; case 5:
cout<<“D”;
switch(choice){
break;
case 9:
case 4:
cout<<“A”;
case 3:
break;
case 2:
case 8:
cout<<“B”; case 1:
break; case 0:
case 7: cout<<“F”;
cout<<“C”; break;
break; default:
cout<<"Invalid score";
28 }
Switch vs. if …else if Statements
switch (expression) {
case val1: if (expression == val1)
statement statement
break;
case val2: else if (expression==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.
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(condition)
{
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 #include <iostream>
using namespace std;
int main (){
int a = 10;
while( a < 20 ){
cout << "value of a: " << a << endl;
a++;
}
return 0;
32 }
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;
int 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;
return 0;
33 }
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 …
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 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++){
cout << "value of a: " << a << endl;
}
return 0;
}
}
39
The for vs. while statements
If the loop-continuation-condition in a for loop is omitted, it is
40
The do…while statement
Is similar to the while statement, except that its body is
executed first and then the loop condition is examined.
the body of the loop will be executed at lease once. Then the condition
will be tested.
The general form is:
do
{
statement;
}
while(expression);
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;
int 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;
return 0;
43 }
Types of loops
Count controlled loops
Repeat a statement or block a specified number of times.
Count-controlled loops contain
▪ An initialization of the loop control variable
▪ An expression to test if the proper number of repetitions has been
completed
▪ An update of the loop control variable to be executed with each
iteration of the body
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
Flag controlled:
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.
A while 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.
A do-while loop can be used to replace a while loop if the
loop body has to be executed before testing the continuation
condition.
46
Caution
Adding a semicolon at the end of the for and while clause before
the loop body is a common mistake, as shown below:
Logic Error
for (int i=0; i<10; i++);
cout<<"i is " + i);
int i=0;
do {
cout"i is " + i);
i++; Correct
} while (i<10);
47
The Labeled Statements
To transfer program control directly to a given
statement, the statement must be labeled
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
Identifiers used as labels can’t be used anywhere in the program
48
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;
.. .
label: statement;
49
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 followed by a
colon (:).
#include <iostream.h>
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 } Example
50
The continue statement
The continue statement
terminates the current iteration of a loop and instead jumps to the next
iteration.
It is an error to use the continue statement outside a loop.
In while and do while loops, the next iteration commence from the
loop condition.
In a “for” loop, the next iteration commences from the loop’s third
expression.
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 the “for” loop, and
for(i=0;i<n;i++) not to the “while” loop.
{
cin>>num;
if(num<0)
continue; //causes a jump to : i++
}
}
52
Statement Labels and continuing with Labels..
outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
continue outer;
}
}
53
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, 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!!”;
break;
}
}
54
The break statement
#include<iostream.h>
Example int main ()
{
Write a c++ program that for (int i=2; i<100; i++)
prints prime numbers less {
bool prime=true;
than 100. for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
}
55
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;
}
}
56
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.
57
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 c++ programs that gives the following outputs
58
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.
59
Brain Teaser
int A=1,B=2;
if (((A==1 )||(B==2))&&(B==0))
cout<<"This exam was difficult";
else
cout<<"This exam was easy";
int A=1,B=2;
if (((A==1 )||(B==2)&&(B==0)))
cout<<"This exam was difficult";
else
60 cout<<"This exam was easy";
Assignment 1
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.
61
Assignment 1…
3. 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.
4. Write c++ programs that gives the following outputs.
62