Programming chapter 3
Programming chapter 3
January, 2013
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.
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:
Page | 1
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
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;
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
Page | 4
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
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:
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.
Page | 5
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
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 | 6
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
Statement1;
Statement2;
statementN;
}
The while loop has two important parts: An expression that is tested for a true or
false value and a statement or a block that is repeated as long as the expression is
true. First expression (called the loop condition) is evaluated. If the outcome is
nonzero then statement (called the loop body) is executed and the whole process is
repeated. Otherwise, the loop is terminated.
For example, suppose we wish to calculate the sum of all numbers from 1 to
some integer denoted by n. This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
sum += i++;
For n set to 5, the table below provides a trace of the loop by listing the
values of the variables involved and the loop condition.
Iteration i n i <= n sum += i++
First 1 5 1 1
Second 2 5 1 3
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0
Page | 7
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
{
statements;
}while (expression);
First statement statements are executed and then expression is evaluated. If the
outcome of the latter is nonzero then the whole process is repeated. Otherwise,
the loop is terminated.
The do loop is less frequently used than the while loop. It is useful for situations
where we need the loop body to be executed at least once, regardless of the loop
condition. For example, suppose we wish to repeatedly read a value and print its
square, and stop when the value is zero. This can be expressed as the following
loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
The ‘for’ Statement
The third type of loop in C++ is the for loop. The for statement (also called for
loop) is similar to the while statement, but has two additional components: an
expression which is evaluated only once before everything else, and an
expression which is evaluated once at the end of each iteration. The general form
of the for statement is:
for(initialization; test_condition; update)
{
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.
Page | 8
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
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 | 9
Fundamentals of Programming
January, 2013
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) #include <iostream.h>
(3,1) int main () 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
(3,2) {
(3,3) int n;
for (n=10; n>0; n--)
3.3. Jumping {
cout << n << ", ";
Statements if (n==3)
{
The break statement cout << "countdown
aborted!";
break; Page | 10
}
}
return 0;
}
Fundamentals of Programming
January, 2013
Chapter Three Control Flow Statements
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?):
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:
#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;
}
#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 | 12