Chapter 3-Flow Control Statements
Chapter 3-Flow Control Statements
2023
Chapter Three Control Flow Statements
3.1. Introduction
In real world, several activities are initiated (sequenced) or repeated based on decisions. Such
activities can be programmed by specifying the order in which computations are carried out.
Control flow refers to the order in which the individual statements, instructions or function calls
of a program are executed or evaluated. A control flow statement is an instruction that can cause
a change in the subsequent control flow to differ from the natural sequential order in which the
instructions are listed. The kinds of control flow statements available in C++, roughly
categorized by their effect, are:
Conditional /selection statements -for executing a set of statements only if some
condition is met
Looping statements- for executing a set of statements zero or more times, until some
condition is met
Jumping statements- for continuation at a different statement
3.2. Conditional Statements
It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied. The C++ if and switch statements provide the way of expressing this.
3.2.1. The if Statement
The if statement causes other statements to execute only under certain conditions. The general
syntax of the if statement is:
if (expression)
statement;
First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise,
nothing happens. For example, when dividing two values, we may want to check that the
denominator is nonzero:
if (count != 0)
average = sum / count;
To make multiple statements dependent on the same condition, we can use a compound
statement:
if (balance > 0) {
interest = balance * creditRate;
Page | 1
Programming I
2023
Chapter Three Control Flow Statements
balance += interest;
}
A variant of if statement that allows us to specify two alternative statements: one which is
executed if a condition is satisfied and one which is executed if the condition is not satisfied is
called the if-else statement and has the general form:
if (expression)
{
statement1;
}
else
{
statement2;
}
First expression is evaluated. If the outcome is nonzero then statement1 is executed. Otherwise,
statement2 is executed.
For example:
if (num > 0)
{
cout<< “Positive number:”;
}
else
{
cout<< “Negative number:”;
}
3.2.2. Nested if Statement
A nested if statement is an if statement in the conditionally executed code of another if
statement. Anytime an if statement appears inside another if statement, it is considered as nested.
if(a>b)
{
if(b>c)
cout<< “a is the greatest”;
}
Actuality the if-else if structure is a nested if statement
Example
#include<iostream.h>
Page | 2
Programming I
2023
Chapter Three Control Flow Statements
int main()
{
//Declaring the necessary variables……..
float mark;
//Asking the user for the mark of the student……….
cout <<”\n\tTHIS PROGRAM WILL HELP YOU TO DETERMINE LETTER GRADE”
<<“ OF STUDENTS”;
cout<< “\n\n”<< “Please enter the mark of the student: ”;
cin>> mark;
//Computing the letter grade………………….
if (mark>=85 && mark<=100)
cout<< “\nThe letter grade of this student is A”;
else if (mark>=70 && mark<85)
cout<< “\nThe letter grade of this student is B”;
else if (mark>=50 && mark<70)
cout<< “\nThe letter grade of this student is C”;
else if (mark>=35 && mark<50)
cout<< “\nThe letter grade of this student is D”;
else if (mark>=0 && mark<35)
cout<< “\nThe letter grade of this student is F”;
else
cout<< “\nSorry, this is an invalid mark value.”;
return 0;
}
3.2.3. The switch Statement
The switch statement provides a way of choosing between a set of alternatives, based on the value
of an expression. The switch statement is mainly used to replace multiple if-else sequence which
is hard to read and hard to maintain. The general form of the switch statement is:
switch (expression)
{
case constant1:
statements;
Page | 3
Programming I
2023
Chapter Three Control Flow Statements
break;
...
case constant n:
statements;
break;
default:
statements;
}
The expression (called the switch tag) following the switch keyword is an integer valued
expression. The value of this expression decides the sequence of statements to be executed. Each
sequence of statements begins with the keyword case followed by a constant integer (called case
labels). (Note that constant characters may also be specified). The keyword break is used to
delimit the scope of the statements under a particular case. The final default case is optional and is
exercised if none of the earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its three components
and stored these in variables operators, operand1, and operand2. The following switch statement
performs the operation and stores the result in result.
switch (operators) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
As illustrated by this example, it is usually necessary to include a break statement at the end of
each case. 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 example, if
we extend the above statement to also allow x to be used as a multiplication operator, we will
have:
Page | 4
Programming I
2023
Chapter Three Control Flow Statements
switch (operator)
{
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case 'x':
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Because case 'x' has no break statement, when this case is satisfied, execution proceeds to the
statements of the next case and the multiplication is performed.
It should be obvious that any switch statement can also be written as multiple if-else
statements. The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
However, the switch version is arguably neater in this case. In general, preference should be
given to the switch version when possible. The if-else approach should be reserved for situation
where a switch cannot do the job (e.g., when the conditions involved are not simple equality
expressions, or when the case labels are not numeric constants).
Page | 5
Programming I
2023
Chapter Three Control Flow Statements
3.3. Looping Statements
A loop is a control structure that causes a statement or group of statements to repeat. C++ has
three looping control structures: the while loop, the do…while loop and the for loop. The
difference between each of these is how they control repetition.
Page | 6
Programming I
2023
Chapter Three Control Flow Statements
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0
Page | 7
Programming I
2023
Chapter Three Control Flow Statements
statement/s;
}
The initialization is an assignment statement that is used to set the loop control variable.
The test_condition is a relational expression that determines when the loop exit.
The update defines how the loop control variable changes each time the loop is repeated.
The for loop continues to execute as long as the condition is true. Once the condition becomes
false, program execution resumes on the statement following the for. In the following program, a
for loop is used to print the numbers 1 through 100 on the screen:
#include <iostream.h>
int main() {
int x;
for(x=1; x <= 100; x++)
cout<< x<<”\t”;
return 0;
}
In the loop, x is initially set to 1 and then compared with 100. Since x is less than 100, cout is
called and the loop iterates. This causes x to be increased by 1 and again tested to see if it is still
less than or equal to 100. If it is, x is displayed. This process repeats until x is greater than 100, at
which point the loop terminates. In this example, x is the loop control variable, which is changed
and checked each time the loop repeats. The following example is a for loop that iterates
multiple statements:
for(x=100; x != 65; x -= 5)
{
z = x*x;
cout<< "The square of "<< x<< “ = ”<< z;
}
Both the squaring of x and the displaying operations are executed until x equals 65. Note that the
loop is negative running: x is initialized to 100 and 5 is subtracted from it each time the loop
repeats.
C++ allows the first expression in a for loop to be a variable definition. In the following example
which calculates the sum of all integers from 1 to n , i is defined inside the loop itself:
Page | 8
Programming I
2023
Chapter Three Control Flow Statements
sum = 0;
for (int i = 1; i <= n; ++i)
sum += i;
Any of the three expressions in a for loop may be empty. For example, removing the first and
the third expression gives us something identical to a while loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; // something;
Removing all the expressions gives us an infinite loop. This loop's condition is assumed to be
always true:
for (;;) // infinite loop
something;
For loops with multiple loop variables are not unusual. In such cases, the comma operator is
used to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;
Because loops are statements, they can appear inside other loops. In other words, loops can be
nested. For example,
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";
produces the product of the set {1,2,3} with itself, giving the output:
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
3.4. Jumping Statements
3.4.1. The break statement
Page | 9
Programming I
2023
Chapter Three Control Flow Statements
#include <iostream.h>
int main () 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
return 0;
}
Using break we
can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite
loop, or to force it to end before its natural end. For example, we are going to stop the count
down before its natural end (maybe because of an engine check failure?):
#include <iostream.h>
int main () 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Page | 10
Programming I
2023
Chapter Three Control Flow Statements
nesting limitations. The destination point is identified by a label, which is then used as an
argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For example,
here is our countdown loop using goto:
#include <iostream.h>
int main () 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}
Page | 11