Chapter 3: Control Statements
Introduction
• Statements in a C++ program normally execute from
top to bottom, in the same order as they appear in
your source code file.
• A program control flow statement modifies the order
of statement execution.
• Program control flow statements can cause other
program statements to execute multiple times or to
not execute at all, depending on the circumstances.
• The selection statements are if, if…else, nested if…
else and switch.
• The term conditional statement is often used in place
• The iteration statements are while, for, and do…
while. These are also commonly called loop or
iteration statements.
• The jump statement is break.
• Block statements are simply blocks of code. (A
block begins with a { and ends with a }.)
• Block statements are also referred to as compound
statements.
• Many C++ statements rely on a conditional
expression that determines what course of action is
to be taken.
• The conditional expression evaluates to either a
true or false value.
Selection
• C++ supports four types of selection statements: if, if…else,
nested if…else and switch. Let us discuss.
1. The if statement
• In its basic form, the if statement evaluates an expression
and directs program execution depending on the result of
that evaluation.
The form of an if statement is as follows:
if (expression)
statement;
• If expression evaluates to true, statement is executed. If
expression evaluates to false, statement is not executed.
• You could say that execution of statement depends on the
result of expression.
• An if statement can control the execution of multiple
statements through the use of a compound statement or
block.
• A block is a group of two or more statements enclosed in
braces.
• A block can be used anywhere a single statement can be used.
Therefore, you could write an if statement as follows:
if (expression)
{
statement1;
statement2;
/* additional code goes here */
Statement n;
}
• Do not make the mistake of putting a semicolon at the end of
an if statement. An if statement should end with the
conditional statement that follows it.
Following programs illustrates the use of if statements.
Demonstration of if statement
#include<iostream.h>
main()
{
int a=5;
if(a > 10) //if statement evaluates to false
{
cout<<” Hello\n”;
}
cout<<” How are you”;
• In the above example there is an integer type
variable a having value 5. When if statement
executes the variable a will be replaced by the value
5.
• Now the expression will look like if(5>10). As we
know 5 is not greater than 10, so this expression
evaluates FALSE.
• This will force compiler to ignore if block and jump
to the line following if block. Hence output will be
“How are you”.
Let us take a look of the following program.
Demonstration of if statement
#include<iostream.h>
main()
{
int a=5;
if(a < 10) //if statement evaluates to true
{
cout<<” Hello\n”;
}
cout<<” How are you”;
}
Output
Hello
• In the above example there is an integer type variable
a having value 5. When if statement executes the
variable a will be replaced by the value 5.
• Now the expression will look like if(5<10). As we know
5 is less than 10, so this expression evaluates TRUE.
• This will force compiler to execute if block and then
the line following if block. Hence output will be
Hello
How are you
NOTE: You will notice that the statements within an if
clause are indented. This is a common practice to aid
readability
2. The if…else statement
• An if statement can optionally include an else clause. The else
clause is included as follows:
if (expression)
statement1;
else
statement2;
• If expression evaluates to true, statement1 is executed. If
expression evaluates to false, statement2 is executed. Both
statement1 and statement2 can be compound statements or
blocks.
• At a time either statement1 or statement2 will be executed
depending on the truth value of if expression.
• Both statement1 and statement2 cannot be executed same
time.
Demonstration of if…else statement
#include<iostream.h>
main()
{
int a=5;
if(a > 10) //if statement evaluates to false
{
cout<<” Hello”;
}
else
{
cout<<” How are you”;
}
}
Output
• In the above example there is an integer type
variable a having value 5. When if statement
executes the variable a will be replaced by the value
5.
• Now the expression will look like if(5>10). As we
know 5 is not greater than 10, so this expression
evaluates FALSE.
• This will force compiler to ignore if block and
execute else block. Hence output will be
“How are you”.
Let us take a look of the following program.
Demonstration of if…else statement
#include<iostream.h>
main()
{
int a=5;
if(a < 10) //if statement evaluates to true
{
cout<<” Hello”;
}
else
{
cout<<” How are you”;
}
}
Output
• In the above example there is an integer type
variable a having value 5. When if statement
executes the variable a will be replaced by the value
5.
• Now the expression will look like if(5<10). As we
know 5 is less than 10, so this expression evaluates
TRUE.
• This will force compiler to execute if block and
ignore else block. Hence output will be
“Hello”.
Demonstration of if…else statement
#include<iostream.h>
main()
{
int age;
cout<<”Please enter your age: ”;
cin>>age; //this will prompt the user to enter his age
if(age <= 40) //if statement can evaluate either true or false depending on the
user input
{
cout<<” You are young”;
}
else
{
cout<<”You are getting old”;
}
cout<”\nThanks”;
Output 1
Please enter your age: 35
You are young
Thanks
Output 2
Please enter your age: 55
You are getting old
Thanks
• In the above example we have declared an integer type variable age. The
program asks the user to enter his age.
• Let us assume, user has entered his age 35. When if statement executes the
variable age will be replaced by the value entered by the user i.e. 35.
• Now the expression will look like if(35<=40). As we know 35 is less than 40, so
this expression evaluates TRUE.
• This will force compiler to execute if block and ignore else block. The last
statement cout<<”\nThanks” is neither in if block nor in else. This statement
is free from any conditional statement. This line will always executes whether
if statement evaluates TRUE or FALSE.
A program to check even and odd numbers.
#include<iostream.h>
main()
{
int n;
cout<<”Please enter any integer number: ”;
cin>>n; //this will prompt the user to enter a number
if(n%2 == 0) //if statement can evaluate either true or false depending on the
user input
{
cout<<”The number is even”;
}
else
{
cout<<”The number is odd”;
}
cout<”\nThanks”;
Output 1
Please enter any integer number: 12
The number is even
Thanks
Output 2
Please enter any integer number: 15
The number is odd
Thanks
• In the above example we have declared an integer type variable n. The
program asks the user to enter any integer number.
• Let us assume, user has entered 12. This value will store in the variable
n. When if statement executes the variable n will be replaced by the
value entered by the user i.e. 12.
• Now the expression will look like if if(12%2 == 0). As we know 12%2 is 0.
Now the if statement will be if(0 == 0) which evaluates TRUE.
• This will force compiler to execute if block and ignore else block. The last
statement cout<<”\nThanks” is neither in if block nor in else block.
3. Nested if…else
• Any statement can be used in an if or else clause, even another if or else
statement. This is called nesting if…else statements.
• Thus, you might see complex if statements in the following form:
if (expression1)
{
if (expression2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
• This cumbersome if statement says, "If expression1
is true and expression2 is true, execute statement1.
• If expression1 is true but expression2 is not true,
then execute statement2.
• Finally, if expression1 is not true, execute
statement3." As you can see, complex if statements
can be confusing!
Following example illustrates nested if…else.
//A program to find greatest number out of three numbers
using nested if…else.
#include<iostream.h>
main()
{
int a, b, c;
cout<<”Please enter first number: ”;
cin>>a; //this will prompt the user to enter a number
cout<<”Please enter second number: ”;
cin>>b; //this will prompt the user to enter another number
cout<<”Please enter third number: ”;
cin>>c; //this will prompt the user to enter third number
if(a > b) //if statement can evaluate either true or false depending on the user input
{
if(a > c)
{
cout<<”The greatest number is ”<<a;
}
else
{
cout<<”The greatest number is ”<<c;
}
else
{
if(b > c)
{
cout<<”The greatest number is ”<<b;
}
else
{
cout<<”The greatest number is ”<<c;
}
}
Output 1
• Please enter first number: 12
• Please enter first number: 7
• Please enter first number: 11
• The greatest number is 12
Output 2
• Please enter first number: 2
• Please enter first number: 7
• Please enter first number: 20
• The greatest number is 20
Output 3
• Please enter first number: 9
• Please enter first number: 27
• Please enter first number: 11
The switch statement
• C++'s most flexible program control statement is the
switch statement, which lets your program execute
different statements based on an expression that
can have more than two values.
• Earlier control statements, such as if, were limited
to evaluating an expression that could have only
two values: true or false.
• To control program flow based on more than two
values, you had to use multiple nested if
statements, as shown in above program.
• The switch statement makes such nesting
unnecessary.
• The general form of the switch statement is as
follows:
switch (expression)
{
case template_1: statement(s);
break;
case template_2: statement(s);
break;
...
case template_n: statement(s);
break;
default: statement(s);
• In this statement, expression is any expression
that evaluates to an integer value: type long, int,
or char.
• The switch statement evaluates expression and
compares the value against the templates
following each case label, and then one of the
following happens:
1. If a match is found between expression and one
of the templates, execution is transferred to the
statement that follows the case label.
2. If no match is found, execution is transferred to
the statement following the optional default label.
// A program demonstrating switch statement.
#include<iostream.h>
main()
{
int n;
cout<<”Please enter any number: ”;
cin>>n; //this will prompt the user to enter a number
switch (n)
{
case 1: cout<<”You have entered 1;
break;
case 2: cout<<”You have entered 2;
break;
case 3: cout<<”You have entered 3;
break;
default: cout<<”You have entered a number that is not between 1 and 3;
}
}
// Using the switch statement to execute a menu system.
#include<iostream.h>
main()
{
int n;
float a, b, c;
cout<<”Please enter first number: ”;
cin>>a; //this will prompt the user to enter a number
cout<<”Please enter second number: ”;
cin>>b; //this will prompt the user to enter second numb
cout<<”Enter 1 for Addition\n”;
cout<<”Enter 2 for Subtraction\n”;
cout<<”Enter 3 for Multiplication\n”;
cout<<”Enter 4 for Division\n”;
cout<<”Enter your choice: ”;
cin>>n;
switch (n)
{
case 1: c = a + b;
cout<<”Addition = “<<c;
break;
case 2: c = a - b;
cout<<”Subtraction = “<<c;
break;
case 3: c = a * b;
cout<<”Multiplication = “<<c;
break;
case 4: c = a / b;
cout<<”Division = “<<c;
break;
default: cout<<”Wrong choice”;
}
}
Iteration (Looping)
• Many programming problems are solved by
repeatedly acting on the same data.
• Iteration means doing the same thing again and again.
The for loop
• The for loop is a C++ programming construct that
executes a block of one or more statements a certain
number of times.
A for statement has the following structure:
for ( initial; condition; increment )
{
statement;
}
• Initial, condition, and increment are all C++
expressions, and statement is a single or compound
C++ statement.
When a for statement is encountered during program
execution the following events occur.
1. The expression initial is evaluated. initial is usually
an assignment statement that sets a variable to a
particular value.
2. The expression condition is evaluated. condition is
typically a relational expression.
3. If condition evaluates to false (that is, as zero), the
for statement terminates.
4. If condition evaluates to true (that is, as nonzero),
the C++ statement(s) in statement are executed.
5. The expression increment is evaluated, and
execution returns to step 2.
Note that statement never executes if condition is
false the first time it's evaluated.
Here is a simple example. Let us suppose you want to
write a C++ program to print HELLO five times.
Following example shows the program without using
loop.
// A program to print HELLO five times without using a
loop.
#include<iostream.h>
main()
{
cout<<”HELLO\n”;
cout<<”HELLO\n”;
cout<<”HELLO\n”;
cout<<”HELLO\n”;
cout<<”HELLO\n”;
}
• Following example uses a for statement to print
HELLO five times on the screen.
// A program to print HELLO five times using for loop.
#include<iostream.h>
main()
{
int i;
for(i = 1; i <= 5; i++)
{
cout<<”HELLO\n”;
}
}
• Line 1 includes the standard input/output header
file.
• Line 4 declares a type int variable, named i, that will
be used in the for loop.
• Lines 5, 6, 7 and 8 are the for loop. When the for
statement is reached, the initial statement is
executed first.
• In this program, the initial statement is i = 1. This
initializes i so that it can be used by the rest of the
loop.
• The second step in executing this for statement is
the evaluation of the condition i <= 5. Because i was
just initialized to 1, you know that it is less than 5.
• So the statement in the for command, the
cout<<”HELLO\n”, is executed.
• After executing the printing function, the increment
expression, i++, is evaluated. This adds 1 to i,
making it 2.
• Now the program loops back and checks the
condition again. If it is true, the cout<<”HELLO\n”
reexecutes, the increment adds to i (making it 3),
and the condition is checked.
• This loop continues until the condition evaluates to
false, at which point the program exits the loop.
• The for statement is frequently used, as in the
previous example, to "count up," incrementing a
counter from one value to another.
• You also can use it to "count down," decrementing
(rather than incrementing) the counter variable.
Following program prints HELLO five times using
decrementing counter.
// A program to print HELLO five times using for loop
(Decrementing counter).
#include<iostream.h>
main()
{
int i;
for(i = 5; i >= 1; i--)
{
cout<<”HELLO\n”;
}
}
• The for statement is quite flexible. For example, you
can omit the initialization expression if the test
variable has been initialized previously in your
program.
• You still must use the semicolon separator as
shown, however.
count = 1;
for ( ; count < 1000; count++)
• The initialization expression doesn't need to be an
actual initialization; it can be any valid C++
expression. Whatever it is, it is executed once when
the for statement is first reached.
• The test expression that terminates the loop can be
any C++ expression. As long as it evaluates to true
(nonzero), the for statement continues to execute.
// A program to print numbers from 1 to 10 using for
loop.
#include<iostream.h>
main()
{
int i;
for(i = 1; i <= 10; i++)
{
cout<<i <<endl;
}
}
// A program to print numbers from 10 to 1 (reverse
order) using for loop.
#include<iostream.h>
main()
{
int i;
for(i = 10; i >= 1; i--)
{
cout<<i <<endl;
}
}
The while loop
• The while loop, also called the while statement,
executes a block of statements as long as a specified
condition is true.
The while statement has the following form:
while (condition)
{
statements
}
• Condition is any C++ expression, and statement is a
single or compound C++ statement.
When program execution reaches a while statement,
1. The expression condition is evaluated.
2. If condition evaluates to false (that is, zero), the
while statement terminates.
3. If condition evaluates to true (that is, nonzero), the
C++ statement(s) are executed.
4. Execution returns to step 1.
Note that statement never executes if condition is
false the first time it's evaluated.
Let us suppose you want to write a C++ program to
print HELLO five times using while loop.
A program to print HELLO five times using while loop.
#include<iostream.h>
main()
{
int i=1;
while(i <= 5)
{
cout<<”HELLO\n”;
i++;
}
}
• Line 1 includes the standard input/output header file.
• Line 4 declares a type int variable, named i and initialized
with value 1, that will be used in the while loop.
• Lines 5, 6, 7, 8 and 9 are the while loop. When the while
statement is reached the condition i <= 5 checked. Because
i was just initialized to 1, you know that it is less than 5, so
the statement in the while command, the cout<<”HELLO\
n”, is executed.
• After executing the printing function, the increment
expression i++, is evaluated. This adds 1 to i, making it 2.
Now the program loops back and checks the condition
again.
• If it is true, the cout<<”HELLO\n” reexecutes, the
increment adds to i (making it 3), and the condition is
checked.
• This loop continues until the condition evaluates to
false, at which point the program exits the loop.
• You might have noticed that a while statement is
essentially a for statement without the initialization
and increment components.
• Because of this equality, anything that can be done
with a for statement can also be done with a while
statement.
• When you use a while statement, any necessary
initialization must first be performed in a separate
statement, and the updating must be performed by
a statement that is part of the while loop.
• When you use a while statement, any necessary
initialization must first be performed in a separate
statement, and the updating must be performed by a
statement that is part of the while loop.
• When initialization and updating are required, most
experienced C++ programmers prefer to use a for
statement rather than a while statement.
• This preference is based primarily on source code
readability. When you use a for statement, the
initialization, test, and increment expressions are
located together and are easy to find and modify.
• With a while statement, the initialization and update
expressions are located separately and might be less
// A program to print even numbers between 1and 10 using
while loop.
#include<iostream.h>
main()
{
int i=1;
while(i <= 10)
{
if(i % 2 == 0)
{
cout<<i <<endl;
}
i++;
}
The do...while Loop
• C++'s third loop construct is the do...while loop,
which executes a block of statements as long as a
specified condition is true.
• The do...while loop tests the condition at the end of
the loop rather than at the beginning, as is done by
the for loop and the while loop.
The structure of the do...while loop is as follows:
do
{
statement
}
• condition is any C++ expression, and statement is a single
or compound C++ statement.
• When program execution reaches a do...while statement,
the following events occur:
1. The statements in statement are executed.
2. Condition is evaluated. If it's true, execution returns to
step 1. If it's false, the loop terminates.
• The statements associated with a do...while loop are
always executed at least once. This is because the test
condition is evaluated at the end instead of the beginning
of the loop.
• In contrast, for loops and while loops evaluate the test
condition at the start of the loop, so the associated
statements are not executed at all if the test condition is
// A program to print HELLO five times using do…while
loop.
#include<iostream.h>
main()
{
int i=1;
do
{
cout<<”HELLO\n”;
i++;
} while(i <= 5);
}
• Line 1 includes the standard input/output header file.
• Line 4 declares a type int variable, named i and initialized
with value 1, that will be used in the do…while loop.
• Lines 5, 6, 7, 8 and 9 are the do…while loop. Note that
the condition is at the end of the loop, so without
checking the condition the statements inside the loop
will be executed.
• When the do…while statement is reached the condition i
<= 5 checked. Because i was just incremented by 1, the
value of i is now 2 which is less than 5, so the the
program loops back and re-executes the do…while
statements again.
• This loop continues until the condition evaluates to false,
at which point the program exits the loop and continues
// A program to print number even though the
condition is false using do…while loop.
#include<iostream.h>
main()
{
int i=10;
do
{
cout<<i <<endl;
i++;
}
while(i <= 5);
Nested Loops
• The term nested loop refers to a loop that is
contained within another loop. You have seen
examples of some nested statements.
• C++ places no limitations on the nesting of loops,
except that each inner loop must be enclosed
completely in the outer loop; you can't have
overlapping loops.
• When you use nested loops, remember that
changes made in the inner loop might affect the
outer loop as well.
• Note, however, that the inner loop might be
independent from any variables in the outer loop
• Good indenting style makes code with nested loops easier to
read.
• Each level of loop should be indented one step further than
the last level. This clearly labels the code associated with
each loop.
• Don't try to overlap loops. You can nest them, but they must
be entirely within each other.
• Do use the do...while loop when you know that a loop should
be executed at least once.
A program to display the following output using nested loop
(one for loop and another while loop).
• 1
• 22
• 333
• 4444
#include<iostream.h>
main()
{
int i, j;
for(i = 1; i <= 4; i++)
{
j = 1;
while(j <= i)
{
cout<<i;
j++;
}
cout<<”\n“;
}