Unit Four: Flow of Control of Program
Unit Four: Flow of Control of Program
Part One
1
Flow Of Control Statement
• A program’s action are regulated by control statements.
• Control statements determine either whether or not other
parts of a program are executed or how many times they
are represented.
• When a programmer crafting a program, it is good practice
to break the program down into pieces that can be thought
of independently.
• Once the program has been completed, we can think of the
execution as being a series of these pieces that work
together in a certain sequence.
• These pieces then pass the control of the program between
each other.
• While one piece has the control, the other pieces are
inactive. This is known as the flow of control in a program.
2
Control Structures
• Normally, statements in a program execute one after the
other in the order in which they are written. This is called
sequential execution.
• Various C++ statements we will soon discuss enable the
programmer to specify that the next statement to execute
may be other than the next one in sequence. This is called
transfer of control.
• All programs are written in three control structures,
namely, the sequence structure, the selection structure and
the repetition structure.
• The term "control structures" comes from the field of
computer science. When we introduce C++'s
implementations of control structures, we will refer to them
in the terminology of the C++ standard document as
"control statements." 3
4
1. Sequence Structure in C++
• Sequential statements are statements that are executed one after the
other in the order they are written.
• In this kinds of statements the flow of control is said to be sequential.
• C++ allows us to have as many actions as we want in a sequence
structure.
Example
#include<iostream.h>
void main()
{
float number1, number2, number3;
cin>>number1;
number2=number1*10;
number3=number1*number2;
cout<<number2<<endl<<number3;
} 5
Activity: 1. Write C++ program to calculate Interest Rate and
current balance of the customers after interest is calculated
and added. Assuming that the interest rate that the bank
gives for the customer is 6%, initial deposit of the
customer is 4400, interest is calculated at the end of each
month.
2. Write C++ program to perform the following mathematical
formula. C=
a 2 b2
• Flow of control, the order in which statements are
executed, so the default flow of control is sequential.
• The two most important alternative statement or structure
that changes the normal flow of control are:
1) Selection (Decision Making)
2) Repetition 6
2. Selection
Testing whether an expression is true or false.
C++ provides three types of selection statements.
• if…selection statement either performs an action if
a condition is true or skips the action if the condition
is false.
• if...else selection statement performs an action if a
condition is true or performs a different action if the
condition is false.
• The switch selection statement performs one of
many different actions, depending on the value of an
integer expression.
7
3. Repetition Statements in C++
• C++ provides three types of repetition statements
(also called looping statements or loops).
• It enable programs to perform statements
repeatedly as long as a condition remains true.
• The repetition statements are the while, do...while
and for …statements.
• The while and for statements perform the action
(or group of actions) in their bodies zero or more
times if the loop-continuation condition is
initially false, the statement will not execute.
• The do...while statement performs the action
(group of actions) in its body at least once.
8
1) if -Selection Statement
• is used to execute a given set of statement or skipped based
on the outcome of test condition.
• The if selection statement is a single-selection statement
because it selects or ignores a single action.
• Syntax
if(condition)
{ •Where condition is an integral
statement1; expression and statement is any
----------- executable statement.
----------
• The statement will be executed
statement n;
only if the value of the integral
expression is nonzero.
}
9
Example 1
1. Write a program that displays “Hello World” on the screen based on the user
input such as the user press y from the keyboard
#include<iostream.h>
#include<conio.h>
int main(){
char ch;
cout<<“Press y to print a message”;
cin>>ch;
if(ch==‘y’ ){
cout<<“Hello”;
cout<<“World \n”;
}
cout<<“Bye”;
getch();
return 0;
}
10
• During the execution of the if statement, the parenthesized
condition or expression is evaluated first.
• If it evaluates true, then the statement is executed and if it
evaluates to false, then the statement is ignored and control
passes to the next statement.
Example2 1. Write C++ program using if-
#include<iostream.h> statement to display the following
main(){ output. Suppose the if condition is,
int a, b; if(code ==1)
The water was too warm
a=10;
The water were all fished out
b=20; It was too late in the season
if(a<b) ***End of Fishing Excuses ***
cout<<“It is true a is less than b”;
}
11
a) Nested Simple if Statement
• The general form or syntax of the nested simple if statement is:
if(condition 1){
statement1a
…………….
if(condition 2){
statement2a
……………….
if(condition3){
statement3a
………………..
}
statement2k
……………..
}
statement1k
……………………….
}
12
• In order for a nested sub statement to be executed, all of the
test conditions of the if’s under which this statement is
nested must be true.
• For example statement3a is only executed if the conditions
1, 2, and 3 all evaluates to true.
• On the other hand, although statement2a is physically
located after the innermost if, it is actually associated with
the second if statement.
• Its execution, therefore, only depends on condition 1 and 2.
• This type of construction can be used to define mutually
exclusive sets .
• The following example can be rewritten using the simple
nested if construction to obtain mutually exclusive
conditions. Error conditions could similarly have been
included using nested simple if’s. 13
#include<iostream.h>
int main(){
int score;
char grade;
cout<<"Enter the score: ";
cin>>score;
if(score >=0){
if(score <=60){
grade='F';
cout<<grade; }
}
if(score>60) {
if(score < =70){
grade='D';
cout<<grade;
} }
if(score>70) {
if(score<=80) {
14
grade='C';
cout<<grade;
}
}
if(score>80) {
if(score <=90) {
grade='B';
cout<<grade;
}
}
if(score>90) {
if(score<=100) {
grade='A';
cout<<grade;
}
}
if(score==101) {
grade='NG';
cout<<grade;
}
return 0;
} 15
2) if-else Statement
• The if..else statement causes one of two alternative
statements to execute depending upon whether the condition
is true.
• The if...else statement is called a double-selection
statement because it selects between two different actions
(or groups of actions).
• Its syntax is
if(condition){
statement 1;
}
else{
statement 2;
} 16
• When the conditional expression evaluates as true,
statement 1 is executed and the else section is
ignored.
• When the if conditional expression evaluates as
false, statement 1 is ignored, and statement 2 is
executed.
• The else section is optional. Without it, however,
construction reverts back into simple if construction.
• After either the else branch(execution of statement
2) or the if branch (execution of statement 1),
control passes to the next statement.
• The exception occurs when a goto is executed in
one of the object statement. 17
Example 1
• The following C++ code determine whether the number
is positive or not:
#include<iostream.h>
#include<conio.h>
int main(){
int n;
cout<<“Enter a number :”;
cin>>n;
if(n>0){
cout<<“The number n is Positive.\n”;
}
18
else{
cout<<“The number n is not Positive. \n”;
}
cout<<“Bye”;
getch();
return 0;
}
Activity
1. Write C++ program to check either a given number is odd or even using if-else
statement
2. Write C++ program to display a message “Excellent” if grade >=90 and “Very
Good” if grade >=80 using if-else statement.
3. Write C++ program to display the following output using if-else statement.
i=3, j=10
i is not greater than 4
k set equal to i
19
4. Determine the output of the following C++ program.
#include<iostream.h>
main(){
int code;
code=2;
if(code !=2){
cout<<“The water was too warm.\n”;
cout<<“The water were all fished out \n”;
}
else{
cout<<“It was too late in the season \n”;
cout<<“The bait was wrong \n”;
}
cout<<“*** End of fishing excuses *** “;
} 20
2.1 Nested- ifs
• A nested if is an if statement that is the target of another if
or else.
• Nested ifs are very common in programming.
• When you nest ifs, the main thing to remember is that an
else statement always refers to the nearest if statement that
is within the same block as the else and that is not already
associated with an else. Here is an example:
if(i = = 10) {
if(j < 20)
a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10) 21
• As the comments indicate, the final else is not associated with if(j<20),
because it is not in the same block (even though it is the nearest if without
an else).
• Rather, the final else is associated with if(i==10).
• The inner else refers to if(k>100), because it is the closest if within the
same block.
• This kind of constructing a program creates a problem called Dangling-
else problem.
• For example when you see the following example:
x=6;
if(x<10)
if(x<5)
cout<<“’Below Average”;
else
cout<<“Invalid”
• Here x is associated with the second if statement.
22
• To associate x in the first if statement use open braces
after the first if statement and the code becomes as
follows:
x=6;
if(x<10)
{
if(x<5)
cout<<“Below average”;
}
else
cout<<“It is invalid”;
• The following C++ program is free from Dangling-else
problem. 23
Example 1
#include<iostream.h>
int main(){
int x;
x=6;
if(x<10){
if(x<5){
cout<<"X is below average. \n";
}
else
cout<<"X is above average.\n";
}
What happens to the output of this
else
program if x is not initialized or x is
cout<<" Invalid";
initialized with a number less than 5
return 0;
and a number greater or equal to 2410
}
B) The if-else-if Statement
• A common programming construct that is based
upon a sequence of nested ifs is the if-else-if
ladder.
• The general form or syntax of if-else-if is looks
like the following:
25
if(condition 1) {
statement 1;
}
else if(condition 2){
statement 2;
}
else if(condition 3) {
statement 3;
}
. . ………………..
else {
statement n;
} 26
• The if statements are executed from the top to
down.
• As soon as one of the conditions controlling the if
is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final
else statement will be executed.
• The final else acts as a default condition; that is,
if all other conditional tests fail, then the last else
statement is performed.
• If there is no final else and all other conditions
are false, then no action will take place.
27
Example 1
• The following C++ program is used to determine whether the number is positive,
negative and zero.
#include<iostream.h>
#include<conio.h>
int main(){
int n;
cout<<“Enter the number n:”;
cin>>n;
if(n>0){
cout<<“The number n is positive. \n”;
}
else if(n<0){
cout<<“The number n is Negative. \n”;
}
28
else{
cout<<“The number n is Zero. \n“;
}
cout<<“ Bye ! Bye!”;
getch();
return 0;
}
Exercise
1. Write C++ program that performs the following input and output
operation . Input Output
A Excellent
B Very Good
C Satisfactory D Not Satisfactory
F Failure
otherwise Invalid Input
29
2. Write C++ program to display a letter grade when users
enters different range of marks. Use the following input
and output information for your work.
Input Output
(marks>=90) and (marks<=100) A
(marks>=70) and (marks<90) B
(marks>=55)and (marks<70) C
(marks>=35)and (marks<55) D
(marks>=1) and (marks<35) F
otherwise NG
30
3) switch-Statement
• The switch selection statement is called a multiple-
selection statement because it selects among many
different actions (or groups of actions).
• The switch statement can be used instead of the else if
construct to implement a sequence of parallel alternatives.
Its syntax is
switch (expression){
case <constant1>:
statementList1;
break;
case <constant2>:
statementList2;
break;
:
: 31
case <constantN>:
statementListN;
break;
……………………
default: statementList0;
}
• This evaluates the expression and then looks for its
value among the case constants.
• If the value is found among the constants listed, then
the statements in the corresponding statementList are
executed.
• Otherwise if there is a default (which is optional), then
the program branches to its statementList.
• The expression must evaluate to an integral type and the
constants must be integral constants. 32
• The expression used in switch statement is any legal C++
expression and the statements are any C++ legal statements or
block of statements.
• Switch evaluates expression and compares the result to each
of the case value.
• Note, however, that the evaluation is only for equality;
relational operators may not be used here.
• If one of the case values matches the expression execution
jumps to those statements and continues to the end of the
switch block, unless a break statement is encountered.
• If nothing matches, execution branches to the optional default
statement.
• If there is no default and there is no matching value, execution
falls through the switch statement and the statement ends.
33
• It is important to note that if there is no break
statement at the end of a case statement,
execution will fall through to the next case
statement.
• This is usually an error.
• If you decide to let execution fall through, be
sure put a comment, indicating that you didn’t
just forget the break.
34
35
1. Write C++ program using switch statement to
perform the following input and output
information.
Input Output
A Excellent
B Very Good
C Satisfactory
D Not Satisfactory
F Failure
otherwise Invalid Output
36
#include<iostream.h>
#include<conio.h>
int main(){
char ch;
cout<<"Enter the Grade :";
cin>>ch;
switch(ch){
case 'A':
cout<<"Excellent \n";
break;
//========================================
case 'B':
cout<<"very Good \n";
break;
//========================================
37
case 'C':
cout<<"Satisfactory \n";
break;
//=======================================
case 'D':
cout<<"Not Satisfactory \n";
break;
//=======================================
case 'F':
cout<<"Failure \n";
break;
default:
cout<<"Invalid Output \n";
}
cout<<"Bye! Bye!";
getch();
return 0;
} 38
Exercise
1. Refer the above program that is implemented using switch
statement. Rewrite the above program assuming that the program
accepts input of upper and lower case letters and display the
same result when accepts both upper and lower case letters.
2. Write C++ program using switch statement to display a letter grade
when users enters different range of marks. Use the following
input and output information for your work.
Input Output
(marks>=90) and (marks<=100) A+
(marks>=80) and (marks<90) A
(marks>=70) and (marks<80) B+
(marks>=65) and (marks<70) B
(marks>=55) and (marks<65) C+
(marks>=45)and (marks<55) C
(marks>=35)and (marks<45) D
(marks>=1) and (marks<35) F
otherwise NG
39
3. Write C++ program using if-else-if or switch statement to
calculate Income Tax, pension and net payment of an
employees. The program is expected to accept salary of an
employee as input and displays income tax, pension, total
deduction and net payment of a salary as output. Use 6% of
Basic salary to compute pension. Use the following
information for tax competition.
Salary Tax
<=150 0
150-650 10%
650-1400 15%
1400-2350 20%
2350-3550 25%
3550-5000 30%
>5000 35%
40