You are on page 1of 52

control structures

The three control structures used in all


structured programming languages are:

1. Sequence
2. Selection (Decision/branching)
3. Iteration (Looping/Repitition)
control structures

 Normally, a program is executed in a


sequential manner. However, in many
cases, a program has to choose among
alternative statements
 C++ provides constructs that enable the
programmer to select which statement in
the program to be executed next.
 The three control structures used in most programming
languages are sequential, selection and iteration

 In Sequential control, the computer executes


instructions that follow one after the other. The program
samples considered earlier are purely sequential

 In Selection control also referred to as branching,


execution is based on a decision. A decision depends
on a boolean test that has to be made before a
computer executes either of the statements. The
boolean test returns either true or false.
 A selection in a program allows us to choose between
two or more actions depending on whether a condition
is true or false. This condition is based on a comparison
of two items
 Selection controls are usually expressed with one
of the following relational operators:
< less than
 greater than
 == equal
 <= less than or equal to
 >= greater than or equal to
 != not equal to

For example, if the boolean test seeks to test if X >


50 and the user enters 60, the value returned is
true.
Selection constructs
 Four selection constructs used in C/C++ are:

 If
 If ..else
 Nested if
 If ..else .. If
If selection control

The if statement.
This evaluates or executes the block of statement
under if; if the boolean expression evaluates to
true and if false the execution will jump to
statement after if block.

1. if (boolean_expression)
{
statement;
statement;
}
statement;
Example1.
#include <iostream>
using namespace std;
int main(void) {
int x, sum;
sum = 100;
cout<<"Please enter an integer number \n";
cin>> x;
if (x!= 0)
sum = sum + x;
cout<<"This is the sum "<< sum;
return 0;
}
The statement:
if ( x != 0) compares the value of x to 0 and has one
alternative, which is executed when x is not equal to 0.
If x is equal to 0, the addition is not performed.
Example2.
 // Get the three test scores.
 // This program averages three test scores
 #include <iostream>
 using namespace std;
 int main()
 {
 int score1, score2, score3; // To hold three test scores
 double average; // To hold the average score

 cout << "Enter 3 test scores and I will average them: ";
 cin >> score1 >> score2 >> score3;

 // Calculate and display the average score.


 average = (score1 + score2 + score3) / 3.0;
 cout << "Your average is " << average << endl;
 // If the average is greater than 95, congratulate the user.
 if (average > 95)
 cout << "Congratulations! That's a high score!\n";
 return 0;
 }

 If the average is greater than 95, the program congratulates the user on obtaining a high
score otherwise no congratulation message.
Selection construct
The if – else statement.
The if/else selection structure allows the
programmer to specify the actions to be performed
when the condition is true and the actions to be
performed when the condition is false.
When the if condition evaluates to true, the true statement
is executed.
When the if condition evaluated to false, the false statement
is executed.
if (expression)
statement or block
else
statement or block
Selection

Example:
Suppose the passing grade on an exam is 60. Write a
program that prints “Passed” if a grade entered is greater
than 60 and “Failed” otherwise.
#include <iostream>
using namespace std;
int main(void) {
int grade;
cout << "Please enter the grade \n";
cin>> grade;
if (grade >= 60)
cout<< "Passed";
else
cout<< "Failed";
return 0;
}
Example2.
Example:
Write a program that prints “your gender” a grade entered is greater
than 60 and “Failed” otherwise.
 #include <iostream>
 using namespace std;
 int main(void) {
 char gender;
 cout<<"enter gender\n";
 cin>>gender;
 if (gender == 'm')
 cout << "your gender is "<< "male";
 else
 cout<< "your gender is "<<"female";
 return 0;
 }
Example3.
 Write a program that uses the modulus operator to determine
 if a number is odd or even. If the number is evenly divisible
 by 2, it is an even number. A remainder indicates it is odd.
 #include <iostream>
 using namespace std;
 int main()
 {
 int number;
 cout << "Enter an integer and I will tell you if it\n";
 cout << "is odd or even. ";
 cin >> number;
 if (number % 2 == 0)
 cout << number << " is even.\n";
 else
 cout << number << " is odd.\n";
 return 0;
 }
Selection construct
Nested if –else
A nested if is an if statement that is inside another if
statement.
To test more than one condition, an if statement can be
nested inside another if statement.
Its execution depends on execution of the outer if.
The general form of nested if is:
if( boolean_expression 1) { // Executes when the
boolean expression 1 is true

if(boolean_expression 2) { // Executes when the


boolean expression 2 is true }
}
Nested if selection example
 #include <iostream>
 using namespace std;
 int main () { // local variable declaration:
 int a = 100;
 int b = 200;
 if( a == 100 ) { // if condition is true then check the following
 if( b == 200 ) { // if condition is true then print the following
 cout<< "the value of b is "<< b<<endl; }
 cout << "the value of a is "<< a<<endl;
 cout<<endl;
 }
 cout << "Exact value of a is : " << a << endl;
 cout << "Exact value of b is : " << b << endl;
 return 0;
 }
Nested if –else

In this nested form, expression_1 is evaluated. If it is FALSE, statement_4 is


executed and the entire nested if statement is terminated; if TRUE, control
goes to the second if (within the first if) and expression_2 is evaluated. If it
is false, statement_3 is executed; if not, control goes to the third if (within
the second if) and expression_3 is evaluated. If it is
false, statement_2 is executed; if not, statement_1 is executed. The
statement_1 (inner most) will only be executed if all the if statement is true.
 #include <iostream>
 #include <stdlib.h>
 using namespace std;
 int main()
 {
 char job_title;
 int years_served, no_of_pub;
 cout<<"Enter data \n";
 cout<<"Current job (Tutor-T, lecturer-L, Assoc prof-A): ";
 cin>>job_title;
 cout<<"Years served: ";
 cin>>years_served;
 cout<<"No of publication: ";
 cin>>no_of_pub;
 if(job_title == 'T')
 {
 if(years_served > 15)
 if(no_of_pub > 10)
 cout<<"\nPromote to lecturer";
 else
 cout<<"\nMore publications required";
 else
 cout<<"\nMore service required";
 }
 else if(job_title == 'L')
 {
 if(years_served > 10)
 if(no_of_pub > 5)
 cout<<"\nPromote to Assoc professor";
 else
 cout<<"\nMore publications required";
 else
 cout<<"\nMore service required";
 }
 else if(job_title == 'A')
 {
 if(years_served > 5)
 if(no_of_pub > 5)
 cout<<"\nPromote to professor";
 else
 cout<<"\nMore publications required";
 else
 cout<<"\nMore service required";
 }
 cout<<"\n";
 system("pause");
 return 0;
 }
If /else –if selection
The If /else –if is a chain of if..else statements. When multipath
decisions are involved, a chain of if –else – if is used.

 Explanation, the if else if statement is an extension of the "if


else" conditional branching statement. When the expression in
the "if" condition is "false" another "if else" construct is used to
execute a set statements based on a expression. This belongs to
Control Structures.
 Syntax:
if (boolean_expression)

statement 1;

else if (boolean_expression)

statement 2

else if (boolean_expression)

statement 3;
else

statements 4;
Statement n;
Example // printing the students' grades based on their marks

#include <iostream>
using namespace std;
int main(void){
int mark;
cout<<"Enter student's mark: ";
cin>>mark;
if (mark < 40)
cout<<"Student grade = F";
else if (mark < 50)
cout<<"Student grade = E";
else if (mark < 60)
cout<<"Student grade = D";
else if (mark < 70)
cout<<"Student grade = C";
else if (mark < 80)
cout<<"Student grade = B";
else if (mark<=100)
cout<<"Student grade = A";
else
cout<<"invalid mark";
return 0;

Selection construct
 Switch selection
 A switch statement allows a variable to be tested for equality
against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.. The
general form is:
switch(expression)
{
caseconstant1:
statementA1
statementA2
...
break;
caseconstant2:
statementB1
statementB2
...
break;
...
default:
statementZ1
statementZ2
...
}
The following rules apply to a switch statement:

 You can have any number of case statements


within a switch. Each case is followed by the
value to be compared to and a colon.

 The constant-expression for a case must be the


same data type as the variable in the switch, and
it must be a constant or a literal.

 When the variable being switched on is equal to a


case, the statements following that case will
execute until a break statement is reached.
 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.

 A switch statement can have an


optional default case, which must appear at the end
of the switch. The default case can be used for
performing a task when none of the cases is true.
No break is needed in the default case.
example
#include <iostream>
using namespace std;
int main (){ // local variable declaration:
char grade;
cout<<"please enter the grade:\n";
cin>>grade;
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
 cout << "Invalid grade" << endl;
 }
 cout << "Your grade is " << grade << endl;

 return 0;
 }
example2
 #include <iostream>
 using namespace std;
 int main (){ // local variable declaration:
 char op;
 int a,b;
 cout<<"enter value of a\n";
 cin>>a;
 cout<<"please enter the operator:\n";
 cin>>op;
 cout<<"enter value of b";
 Cin>>b;
 switch(op) {
 case '*' :
 cout <<a*b;
 break;
 case '+' :
 cout<<a+b;
 break;
 case '-' :
 cout <<a-b;
 break;
 case '/' :
 cout <<a/b;
 break;
 default :
 cout << "Unknown operator" << endl;
 }
 // cout << "Your grade is " << grade << endl;

 return 0;
}
Looping

Loops cause a section of your program


to be repeated a certain number of
times. The repetition continues while a
condition is true. When a condition
becomes false, the loop ends and
control passes to the statements
following the loop. If a loop continues
forever, it is called an infinite loop.

In looping, a sequence of statements is


executed until some condition for the
termination of the loop are satisfied.
There are three kinds of loops in C++:
1. for loop,
2. while loop, and
3. do while loop.
The for loop
The for loop is ideal for performing a known number of
iterations.. The general form of the loop is:

The execution of the for statement is done as, by


firstly initialising the control variables using
assignment statements such as i=0. the variables i
and count are known as loop control variables. the
value of the control variable is tested using the test
condition.
 In general, there are two categories of loops: conditional loops and
count-controlled loops.
 A conditional loop executes as long as a particular condition exists.
For example,
 an input validation loop executes as long as the input value is
invalid. When you write a conditional loop, you have no way of
knowing the number of times it will iterate.
 Sometimes you know the exact number of iterations that a loop
must perform.
 A loop that repeats a specific number of times is known as a
count-controlled loop. For example,
 if a loop asks the user to enter the sales amounts for each month in
the year, it will iterate twelve times. In essence, the loop counts to
twelve and asks the user to enter a sales amount each time it
makes a count.
for (initialisation; test condition; increment)
{

statement;
statement;

} // No semicolon here
The for loop

False
Test Exit

True

Body of loop
 A count-controlled loop must possess three elements:
 1. It must initialize a counter variable to a starting value.
 2. It must test the counter variable by comparing it to a

maximum value. When the


 counter variable reaches its maximum value, the loop

terminates.
 3. It must update the counter variable during each

iteration. This is usually done by incrementing the variable.


 Count-controlled loops are so common that C++ provides

a type of loop specifically for them. It is known as the for


loop. The for loop is specifically designed to initialize, test,
and update a counter variable. Here is the format of the for
loop when it is used to repeat a single statement:
For loop example
 #include <iostream>
 using namespace std;
 int main() {
 for(int x = 0; x < 100; x = x + 1)
 cout << x << "\n";
 return 0;
 }
The for loop
The body of the loop can contain one or
multiple statements. The brace are used to
group the multiple statements..

However it is a good programming practice to


use braces even if there is only one statement
in the body of the loop.
The for loop

 The test condition i is a relational


expression, such as i<100 that determines
when the loop will exit.

 If the condition is true, the body of the loop


is executed; otherwise the loop is
terminated and the execution continues
with the statement that immediately
follows the loop.
The while loop
The test condition is evaluated first and if the
condition is true, the body of the loop is
executed zero or more times. See the flowchart
next slide. After execution of the body, the test
condition is once again evaluated and if it is true,
the body is executed once again.

This process of repeated execution of the body


continues until the test condition finally become
false. On exit, the program continues with the
statement immediately after the body of the
loop.
while loop

Initialize

False
Test Exit

True
True

Body of loop
The general form of the while loop is:
initialization
while(condition)
{
statement1
statement2

incrementation
}
Example 1

 #include <iostream>
 using namespace std;
 int main() {
 int x = 0;
 while(x < 10) {
 cout << x << "\n";
 x = x + 1;
 }
 return 0;
 }
 // This program demonstrates a simple while loop.
 #include <iostream>
 using namespace std;
 int main()
 {
 int number = 1;
 while (number <= 5)
 {
 cout << "Hello\n";
 number++;
 }
 cout << "That's all!\n";
 return 0;}
The while Loop is a Pretest Loop

 The while loop is known as a pretest loop, which means it tests its
expression before each iteration.
 The number variable is initialized with the value 1. If number
had been initialized with a value that is greater than 5, as
shown in the following program segment, the loop would
never execute:
 int number = 6;
 while (number <= 5)
 {
 cout << "Hello\n";
 number++;
 }
 An important characteristic of the while loop is that the loop
will never iterate if the test expression is false to start with.
Infinite Loops

 In all but rare cases, loops must contain


within themselves a way to terminate
 If a loop does not have a way of stopping, it

is called an infinite loop.


 An infinite loop continues to repeat until the

program is interrupted. Here is an example of


an infinite loop:
 int number = 1;
 while (number <= 5)
 cout << "Hello\n";
 // custom countdown using while
 #include <iostream>
 using namespace std;
  
 int main ()
 {
 int n = 10;
  
 while (n>0) {
 cout << n << ", ";
 --n;
 }
  
 cout << "liftoff!\n";
 }
exercise
 Write a program that displays the numbers 1 through 10 and
their squares using while loop.
 #include <iostream>
 using namespace std;
 int main(){
 int num = 1; //Initialize the counter.
 cout << "Number Number_Squared\n";
 cout << "-------------------------\n";
 while (num <= 10){
 cout << num << "\t\t" << (num * num) << endl;
 num++;
 } //Increment the counter.
 return 0;}
Write the out put of this program
#include<iostream>
using namespace std;
int main()
{
int i=0;
int sum=0;
while(i<10)
{
sum=sum+i;
cout<<"The sum of the first "<<i+1<<" natural numbers is
"<<sum<<endl;
i++; //increment count by one
}
return 0;
}
The do .. while loop
Unlike the while loop in which a condition is
test before the loop is executed,
In do– while, the testing is done after the body
of the loop is executed at least once. This
means that the execution is one or more
times.

See the flowchart on the next slide


The do while loop

Body of loop

False
Test Exit

True
The general form of the do loop is:
do
{

statement;
statement;

} // No semicolon here

while (test-condition); // semi colons here


The do-while loop is a posttest loop.
 This means it does not test its expression
until it has completed an iteration. As a
result, the do-while loop always performs at
least one iteration, even if the expression is
false to begin with. This differs from the
behavior of a while loop, which you will recall
is a pretest loop
This process continues as long as the
condition is true. When the condition
becomes false, the loop will be terminated
and the control goes to the statement that
appears immediately after the while
statement. Since the test condition is
evaluated at the bottom of the loop, the
do …. While construct provides an exit
controlled loop and therefore the body of
the loop is always executed at least once.
#include <iostream>
using namespace std;
int main () { // variable declaration:
int a = 10; // do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 ); return 0;
}
User Controlled do while Loop
 Sometimes you want the user to determine the maximum value of the counter variable in
 a do while loop, and therefore determine the number of times the loop iterates.
 #include<iostream>
 using namespace std;
 int main()
 {
 int score1, score2, score3; // Three scores
 double average; // Average score
 char again; // To hold Y or N input

 do
 {
 // Get three scores.
 cout << "Enter 3 scores and I will average them: ";
 cin >> score1 >> score2 >> score3;
 // Calculate and display the average.
 average = (score1 + score2 + score3) / 3.0;
 cout << "The average is " << average << ".\n";

 // Does the user want to average another set?


 cout << "Do you want to average another set? (Y/N) ";
 cin >> again;
 } while (again == 'Y' || again == 'y');
 return 0;
 }

You might also like