Chapter 3-Flow Control
Chapter 3-Flow Control
CHAPTER THREE
FLOW OF CONTROL
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. This term
reflects the fact that the currently executing statement has the control of the CPU, which when
completed will be handed over (flow) to another statement.
Flow control in a program is typically sequential, from one statement to the next. But we can also
have execution that might be divided to other paths by branching statements. Or perform a block
of statement repeatedly until a condition fails by Repetition or looping. Flow control is an
important concept in programming because it will give all the power to the programmer to decide
what to do to execute during a run and what is not, therefore, affecting the overall outcome of the
program.
1. Sequential Statements
Such kinds of statements are instruction in a program which will be executed one after the other in
the order scripted in the program. In sequential statements, the order will be determined during
program development and cannot be changed.
2. Selection Statements
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++, which are the “if statement” and the “switch
statement”.
a) The if Statement
It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied. The different forms of the ‘If” statement will be used to decide whether to execute part of
the program based on a condition which will be tested either for TRUE or FALSE result.The
different forms of the “If” statement are:
The simple if statement
The If else statement
Page 1 of 19 Department of Computer Science & Technology
Compiled by: Wubet N.
([email protected])
Fundamentals of Programming Chapter Three: Flow Of Control
In any “if” statement, first the “expression” will be evaluated and if the outcome is non zero (which
means TRUE), then the “statements” is executed. Otherwise, nothing happens (the statement will
not be executed) and execution resumes to the line immediately after the “if” block.
E.g.:
if(age>18)
cout<<”you are an adult”;
To make multiple statements dependent on the same condition we can use a compound statement,
which will be implemented by embracing the group of instructions within the left “{“ and right “}”
French bracket.
E.g.:
if(balance > 0)
{
interest = balance * creditRate;
balance += interest;
}
Most of the time “expression” will have relational expressions testing whether something is equal,
greater, less, or different from something else.
It should be noted that the output of a relational expression is either True (represented by anything
different from zero) or False (represented by Zero).Thus any expression, whose final result is either
zero or none zero can be used in ”expression”
E.g.:
int x;
cin>>x;
if(x)
cout<<”you are an adult”;
In the above example, the value of variable x will be an input from the user. The “if” statement will
be true if the user gives anything different from zero, which means the message “you are an adult”
will be displayed on the screen. If the user gives zero value for x, which will be interpreted as False,
nothing will be done as the if statement is not satisfied.
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.
First “expression” is evaluated and if the outcome is none zero (true), then “statements1” will be
executed. Otherwise, which means the “expression” is false “statements2” will be executed.
E.g.1:
if(balance > 0)
{
interest = balance * creditRate; E.g.3:
balance += interest; int x;
} cout<<”Enter a number: “;
Else cin>>x;
{ if(x%2==0)
interest = balance * debitRate; cout<<”The Number is Even”;
balance += interest; else
} cout<<”The Number is Odd”;
E.g.2:
if(age>18) E.g.4:
cout<<”you are an adult”; int x;
else cout<<”Enter a number: “;
cout<<”You are a kid”; cin>>x;
if(x%2)
E.g:.2.
#include<iostream.h>
#include<conio.h>
int main()
{
int testScore;
cout<<”\nEnter your test score:”;
cin>>testScore;
False True
testScore < 70?
First “expression1” is evaluated and if the outcome is none zero (true), then “statements1” will be
executed. Otherwise, which means the “expression1” then “expression2” will be evaluated: if the
out put of expression2 is True then “statements2” will be executed otherwise the next “expression”
in the else if statement will be executed and so on.
If all the expressions in the “if” and “else if” statements are False then “statements” under else will
be executed.
The “if…else” and “if…else if” statements are said to be exclusive selection as if one of the
condition (expression) is satisfied only instructions in its block will be executed and the rest will be
ignored.
E.g.:
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”;
In the above example, only one of the five cout statements will be executed and the rest will be
ignored. But until one of the conditions is satisfied or the else part is reached, the expressions will
be tested or evaluated.
if (expression1)
{
if (expression2)
statementsN;
else
statementsM;
}
else
{
if (expression3)
statementsR;
else
statementsT;
}
StatementsN will be executed if and only if “expression1” and “expression2” are evaluated and if
the outcome of both is none zero (TRUE).
StatementsM will be executed if and only if “expression1” is TRUE and “expression2” is FALSE.
StatementsR will be executed if and only if “expression1” is FALSE and “expression3” is TRUE.
StatementsT will be executed if and only if “expression1” is FLASE and “expression2” is FALSE.
Lets have an example on nested if statements
#... getch();
int main() return 0;
{ }
int testScore, age;
cout<<”\n Enter your test score :”;
cin>>testScore;
cout<<“\n enter your age:”;
cin>>age;
False True
testScore >=70?
True False
cout<</;you didn’t pass”; age < 10?
switch(expression)
{
case constant1:
statements;
.
.
case constant n:
statements;
default:
statements;
}
Expression is called the switch tag and the constants preceding each case are called the case
labels. The out put of “expression” should always be a constant value. First expression is
evaluated, and the outcome, which is a constant value, will be compared to each of the numeric
constants in the case labels, in the order they appear, until a match is found.
Note, however, that the evaluation of the switch tag with the case labels is only for equality
The statements following the matching case are then executed. Note the plural: each case may
be followed by zero or more statements (not just one statement).
After one case is satisfied, execution continues until either a break statement is encountered or
all intervening statements are executed, which means until the execution reaches the right
French bracket of the switch statement.
The final default case is optional and is exercised if none of the earlier cases provide a match.
This means that, if the value of the “expression” is not equal to any of the case labels, then the
statements under default will be executed.
Now let us see the effect of including a break statement in the switch statement.
break
false false
true true
N==3? x = 30 N==3? x = 30
false false
break
The break terminates the switch statement by jumping to the very end of it.
There are, however, situations in which it makes sense to have a case without a break. For
instance:
E.g.: switch(operator)
{
case ‘+’: result = operand1 + operand2;
break;
case ‘-’ : result = operand1 – operand2;
break;
case ‘x’:
case ‘*’: result = operand1 * operand2;
break;
Page 10 of 19 Department of Computer Science & Technology
Fundamentals of Programming Chapter Three: Flow Of Control
Because case ‘x’ has no break statement (in fact no statement at all!), when this case satisfied,
execution proceeds to the statements of the next case and the multiplication is performed.
Switch evaluates expression and compares the result to each of the case values. Relational and
Boolean operators can be used in switch tag if and only if the expected output is either 0 to
represent False or 1 to represent True as that is the only possible output from such operators.
3. Repetition Statements/Loops
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:
a) The For Statement or loop
b) The While statement or loop
c) The do…while statement or loop
a) The for statement / loop
The “for” statement (also called loop) is used to repeatedly execute a block of instructions until
a specific condition fails.
The General Syntax is:
statements;
Thus, first expression1 is evaluated and then each time the loop is executed, expression2 is
evaluated. If the outcome of expression2 is non zero then statements is executed and
expression3 is evaluated. Otherwise, the loop is terminated.
In most programs, the “for loop” will be used for such expressions where expression1 is
initialization, expression2 is condition and expression3 is either increment or decrement.
The general format can be expressed as follows for the sake of clarity:
for(initialization ; condition ; increase/decrease)
statement;
Steps of execution of the for loop:
1. Initialization is executed. (will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop finishes and
statement is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is executed and the loop
gets back to step two.
E.g. guess the output of the following code:
int main()
{
for(int i=10;i>0;i--)
{
cout<<n<<“,”;
}
cout<< “FIRE!”;
getch();
return 0;
}
Even though it is not recommended, expression1, expression2 and expression3 can be optional
or can be ignored. This means that they can take NULL statement. But making expression2 null
means that the loop will not terminate. In such cases one can include an “if” statement inside the
“for” loop which will test a condition and break out from the loop using the break statement.
While making one or more of the three expressions null, the semi colons CAN NOT be ignored.
E.g.:
for (;n<10;) //if we want neither initialization nor increase/decrease
for ( ; ; ) //is an infinite loop unless and otherwise there is if statement inside the loop.
It is declared above that expression1 and expression3 can be one or more statements. The
composite statements should be separated by a comma. This means, optionally, using the
comma operator (,) we can specify more than one instruction in any of the two fields included in
a “for” loop.
E.g.:
for(n=0,i=100;n!=i; n++,i--)
{
//whatever here
}
In the above example, n=0 and i=100 will be part of expression1 and will be executed only once
before the loop starts. In addition, n++ and i—will be part of expression3 and will be executed
after each looping/iteration.
Eg:1. //the following for statement adds the numbers between 0 and n
int Sum=0;
for(int i=0; i<=n;i++)
Sum=Sum+i;
Eg:2. //the following for statement adds the even numbers between 0 and n
int Sum=0;
for(int i=0; i<=n;)
{
Sum=Sum+i;
i+=2;
}
Eg:3. // the following for statement adds the even numbers between 0 and n
// where all the three expressions are null.
int Sum=0;
int i=0;
for( ; ; )
{
If(i<=n)
break;
else
{
Sum=Sum+i;
i++;
}
}
Page 13 of 19 Department of Computer Science & Technology
Fundamentals of Programming Chapter Three: Flow Of Control
In the above example, the initialization is at the top before the looping starts, the condition is
put in if statement before the instructions are executed and the increment is found immediately
after the statements to be executed in the loop.
NB: even though there is the option of making all the three expressions null in a “for” loop, it is
not recommended to make the condition to take null statement.
while(expression)
statements;
First expression (called the loop condition) is evaluated. If the outcome is non zero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise, the
loop is terminated.
Suppose that we wish to calculate the sum of all numbers from 1 to some integer value n:
E.g.1: // adds the numbers between 0 and any given number n
i=1;
sum = 0;
while(i <= n)
sum += i++;
E.g.3:
/* the following while loop will request the user to enter his/her age which should be between
0 and 130. If the user enters a value which is not in the range, the while loop test the value and
request the age again until the user enters a valid age. */
cout<<“\n enter your age [between 0 and 130]:”;
cin>>age;
while(age < 0 || age > 130)
{
cout<<“\n invalid age. Plz try again!”;
cin>>age;
}
c) Do…while loop
The do while statement (also called the do while loop) is similar to the while statement, except
that its body is executed first and then the loop condition is examined. In do…while loop, we
are sure that the body of the loop will be executed at least once. Then the condition will be
tested.
The general form is:
do
{
statement;
}
while(expression);
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.
E.g.1: //our previous example (Eg3) in the while loop might be changed as:
age=-1;
do
{
cout<<“\n enter your valid age [between 0 and 130]:”;
cin>>age;
}
while(age < 0 || age > 130);
In the first example, since product is initialized with zero, the expression “product*=5” will
always give us zero which will always be less than 50.
In the second example, the variable counter is initialized to 1 and increment is 2, counter will
never be equal to 10 as the counter only assumes odd values. In theory, this while loop is an
infinite loop, but in practice, this loop eventually terminates because of an overflow error as
counter is an integer it will have a maximum limit.
Off-By-One Bugs (OBOB): another thing for which you have to watch out in writing a loop is
the so called Off-By-One Bugs or errors. Suppose we want to execute the loop body 10 times.
Does the following code work?
E.g.:1
count = 1;
while(count < 10)
{
…
count++;
}
No, the loop body is executed nine times. How about the following?
E.g.:2
count = 0;
while(count <= 10)
{
…
count++;
}
No this time the loop body is executed eleven times. The correct is
E.g.:3
count = 0;
while(count < 10)
{
…
count++;
}
OR
ount = 1;
while(count <= 10)
{
…
count++;
}
E.g.:
for(int n=10;n>0;n--)
{ if(n==5)
continue; //causes a jump to n—
cout<<n<< “,”;
}
When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops. For example, in the following set of nested loops,
the continue statement applies to the “for” loop, and not to the “while” loop.
E.g.:
while(more)
{
for(i=0;i<n;i++)
{ cin>>num;
if(num<0)
continue; // causes a jump to : i++
}
}
Worksheet 3