Chapter 3 – Control statements AMU
Chapter 2
Control Statements
Introduction: depending upon requirements of a problem, it is often required to alter the
normal sequence of execution in the program. This means that we may desire to
selectively/repetitively execute a program statement. A number of C++ control structures,
are available for the flow of processing. We study the control structure under following
topics. A program is usually not limited to a linear sequence of instructions. During
its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides
control structures that serve to specify what has to be done to perform our program.
With the introduction of control sequences we are going to have to introduce a new
concept: the block of instructions. A block of instructions is a group of instructions
separated by semicolons (;) but grouped in a block delimited by curly bracket signs:
{and}. Most of the control structures that we will see in this section allow a generic
statement as a parameter; this refers to either a single instruction or a block of
instructions, as we want. If we want the statement to be a single instruction we do not
need to enclose it between curly-brackets ({}). If we want the statement to be more than a
single instruction we must enclose them between curly brackets ({}) forming a block of
instructions.
Categories of control structure statements
I. Conditional statement
if statement
a. if
b. if…else
c. nested if…else
switch-case statement
II. Repetitive/loop statement
for loop
while loop
do…while loop
Page 1 of 16
Chapter 3 – Control statements AMU
III. Breaking control statement
break statement
continue statement
go to statement
Control statements in C++
Control statements allow decision making within programs. Control statements come in
several different forms to provide flexibility in the controlling of program execution. One
form is to optionally execute C ++ statements. Another form is to form a loop, where all
the statements in a loop are executed repeatedly until the exit condition is satisfied.
Another form is to branch to a certain statement and continue execution.
Conditional statement
Decision making with if statement
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression.
if can be used in different forms depending upon nature of conditional test.
1. if 2. if…else 3. nested – if.
Simple if statement
It is used to execute an instruction or block of instructions only if a condition is fulfilled.
The general form/syntax of a simple if statement is:
if (test expression)
{
statement-block;
}
statement-x;
The ‘statement block’ may be a single statement or a group of statements. If the test
expression is true, the statement-block will be executed; otherwise the statement-block
Page 2 of 16
Chapter 3 – Control statements AMU
will be skipped and the execution will jump to the statement-x. Remember, when the
condition is true both the statement-block and the statement-x are executed in sequence.
For example, the following code fragment prints out x is 100 only if the value stored in
variable x is indeed 100:
if (x = = 100)
cout << "x is 100";
This is illustrated in the following figure.
Entry
Eg., 1) if (x>y)
cout<<” x is greater than y”;
Test False 2) if ((marks>250) && (marks <300))
expression cout << “Second Division”;
?
Program 3) to state the given no is +ve.
//To display number is positive.
True
#include<iostream.h>
void main()
Statement-block {
int num;
cout<<” enter a number\n”;
Statement-x cin>>num;
if (num>0)
Fig: Flowchart of simple if statement cout<<” number is positive”; }
Page 3 of 16
Chapter 4 – Control statements AMU
The if – else statement:
The if…else statement is an extension of the simple if statement. The general
form/syntax is:
if (test expression)
{
True block statement(s);
}
else
{
False block statement(s);
}
statement-x;
If the test expression is true, then the true-block statement(s), immediately following
the if statement are executed; otherwise, the false-block statement(s) are executed. In
either case, either true-block or false-block will be executed, not both. This is
illustrated in the following Fig. In both cases, the control is transferred subsequently
to statement-x.
Eg., 1) if (total>=250)
Entry
cout<<” result Pass”;
else
cout<<” result Fail”;
True Test False Program: To find whether the given
expression number is even or odd.
? // To find whether given number is
even or odd. #include<iostream.h>
void main()
{
True-block False-block int no;
statements statements cout<<”enter a number”;
cin>>no;
if ( no %2 == 0 )
cout<<no<<”is an even number”;
Statement-x
else
cout<<no<<”is an odd number”;
Fig: Flowchart of if…else statement }
Nested if statement
When a series of decisions are involved, we may have to use more than one if…else statement in
nested form as follows:
For G1 Computer science students (2014) Page 4 of 16
Chapter 4 – Control statements AMU
if (test condition 1) Example:
{ // To find whether the given number is +ve or –ve or
if (test condition 2) zero.
{ #include<iostream.h>
statement-1; void main()
} {
else int n;
{ cout<<”Enter any number :”;
statement-2; cin>>n;
} if (n>0)
} cout<<”The given number is +ve”<<endl;
else else if (n<0)
{ cout<<”The given number is negative”<<endl;
statememt-3; else
} cout<<”The given number is zero”;
statement-x; }
If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform
the second test. If the condertion-2 is true, the statement-1 will be evaluated; otherwise the
statement-2 will be evaluated and then the control is transferred to the statement-x.
Example: Write a C++ Program to calculate tax to be paid by an employee based on following
conditions:
(1) income up to 20,000 no tax.
(2) 20,000 < income <= 30, 000 tax = 20% for next 10,000.
(3) 30,000 < income <= 50,000 tax = 30% for next 20,000.
(4) 50,000 < income <=100,000 tax = 40% for next 50,000.
(5) income > 100,000 tax = 50% for remaining part.
#include <iostream.h>
void main ()
{
float income, tax;
cout<<”Enter the total income of the employee\n”;
cin>>income;
if(income<=20000)
tax = 0.0;
else if (income <=30000)
For G1 Computer science students (2014) Page 5 of 16
Chapter 4 – Control statements AMU
tax = (income – 20000) * 0.20;
else if (income <= 50000)
tax=(income-30000) * 0.30 + 2000;
else if (income <= 1000000)
tax = (income –50000) * 0.40 +8000;
else
tax = (income –100000) *.50 +28000;
cout<<"tax = "<<tax;
}
The switch-case statement
This is a multiple branching control statement. It is useful for decision making when more
than one case is involved.
The general form of switch statement is as follows:
switch (expression)
{
case label 1: statement sequence ;
When switch is executed value of expression is
break;
case label 2: statement sequence ; compared against label 1, label 2, label 3 etc. If a
break;
case is found whose value matches the expression,
case label 3: statement sequence ;
break; then sequence of statements that follow the case is
:
executed.
:
default: statement sequence ; The break at the end of each block indicates end
break;
of particular case & causes exit from the switch
}
statement, transferring control to outside the switch
statement.
The default case is optional case. When present, it will be executed if the value of the
expression does not match with any of the case values.
For G1 Computer science students (2014) Page 6 of 16
Chapter 4 – Control statements AMU
Flow chart for switch…case
If expression True 1st case body
equal to 1 executed
Fals
e
True
If expression
2nd case body
equal to 2
executed
Fals
e
True
If expression n th case body
equal to 3 executed
Fals
e default body
executed
// Demonstrates switch
statement #include
<iostream.h>
int main()
{ unsigned short int number;
cout << "Enter a number between 1 and 5: ";
cin >> number;
switch (number)
{ case 0: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!\n"; // fall through
case 4: cout << "Nice Pick!\n"; // fall through
case 3: cout << "Excellent!\n"; // fall through
case 2: cout << "Masterful!\n"; // fall through
For G1 Computer science students (2014) Page 7 of 16
Chapter 4 – Control statements AMU
case 1: cout << "Incredible!\n";
break;
default: cout << "Too large!\n";
//break;
}
return 0;
}
Loop statements
The while loop statement
The simplest of all the looping structures in C++ is the while statement.
The basic format/syntax of the while statement is:
while (test condition)
{
body of the loop;
}
The while is an entry-controlled loop statement. The test-condition is evaluated and if
the condition is true, then the body of the loop is executed. After execution of the
body, the test-condition is once again evaluated and if it is true the body is executed
once again. This process of repeated execution of the body continues until the test-
condition finally becomes false and the control is transferred out of the loop. The
body of the loop may have one or more statements. The braces are needed only if the
body contains two or more statements.
The flowchart of while loop is as
follows:
Yes
while Statements
(Cond)
No
Out of loop
For G1 Computer science students (2014) Page 8 of 16
Chapter 4 – Control statements AMU
Example: Find the sum of even numbers between 1 to n.
#include <iostream.h> output
void main() enter the end number: 5
{ sum=6
int i, n, sum=0;
cout<<"enter the end number:";
cin>>n;
i=2;
while (i <= n)
{
sum = sum + i;
i = i + 2;
}
cout<<"sum= "<<sum;
}
The do-while loop statement
The basic form of the do-while statement is as follows:
do
{
body of the loop;
}
while (test-condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop
first. At the end of the loop, the test-condition in the while statement is evaluated. If
the condition is true, the program continues to evaluate the body of the loop once
again. This process continues as long as the condition is true. When the condition
becomes false; the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
Since the test-condition is evaluated at the bottom of the loop, the do...while provides
an exit-controlled loop and therefore the body of the loop is always executed at least
once.
For G1 Computer science students (2014) Page 9 of 16
Chapter 4 – Control statements AMU
The flowchart of do-while loop is as follows:
do
Example:
#include <iostream.h> output
void main() sum=1
Statements
{
int sum = 0;
int i = 1;
True do
Cond.?
{
sum += i;
False i += 2;
cout<<"Sum="<<sum;
Out of loop }
while (i >= 100);
}
for loop statement
This is used when we know the number of times the instructions are to be executed.
Syntax : for (exp.1; exp.2; exp.3)
{
Sequence of statements;
}
Here exp.1 – initial value
exp.2 – Testing condition,
exp.3 - step value (increment /decrement)
(exp. 1)
No
exp.2;
Yes
Out of for loop
Statements;
exp.3;
For G1 Computer science students (2014) Page 10 of 16
Chapter 4 – Control statements AMU
e.g. - 1. sum = 0;
for (i=0; i <= 100 ; i++) no semicolon
sum += i;
Following steps are involved in the code:
Initialization condition checking body of the loop
increment/ decrement again condition checking.
2. fact = 1;
for (i = 1; i < n ; i++)
fact *= i ;
Program: – To display all odd numbers & their sum up to 50.
#include<iostream.h>
void main()
{
int i , sum = 0;
cout<<”list of odd numbers up to 50:\n”;
for (i=1 ; i <= 50 ; i=i+2)
{
Cout<<i<<” ”;
sum += i;
}
cout<<” \n Sum is:”<< sum;
}
Breaking control statements
Break statement:
The break statement causes an immediate exit from the do, for, switch, and while
statement in which it appears, the program continues executing with the next program
statement following the do, for, switch, and while statement block..
The format of the break statement is simply
break;
The behavior of the break statement is showed below.
For G1 Computer science students (2014) Page 11 of 16
Chapter 4 – Control statements AMU
while (--------) Example: Output:
{ #include<iostream.h> 1 2 3 4 5 6 7 8 9 10
void main()
---------
if (condition) {
break; int i=1;
---------
--------- while (1)
} {
--------
cout<<i<<" ";
if (i==10)
break;
i++;
}
Continue statement
The continue statement tells the compiler, “skip the following statements and
continue with the next iteration.” The continue instruction causes the program to
skip the rest of the loop in the present iteration as if the end of the statement block
would have been reached, causing it to jump to the following iteration.
The format of the continue statement is simply
continue;
The use of the continue statement in loops is illustrated in the following figure. In
while and do loops, continue causes the control to go directly to the test-condition
and then to continue the iteration process. In the case of for loop, the increment
section of the loop is executed before the test-condition is evaluated.
while (--------)
{
if (condition)
continue;
---------
}
For G1 Computer science students (2014) Page 12 of 16
Chapter 4 – Control statements AMU
For example, we are going to skip the number 5 in our countdown:
// continue loop example output
#include <iostream.h> 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5)
continue;
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
The goto instruction
It allows making an absolute jump to another point in the program. You should use
this feature carefully since its execution ignores any type of nesting limitation. The
destination point is identified by a label, which is then used as an argument for the
goto instruction. A label is made of a valid identifier followed by a colon (:). This
instruction does not have a concrete utility 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:
// goto loop example Output
#include <iostream.h> 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0)
goto loop;
For G1 Computer science students (2014) Page 13 of 16
Chapter 4 – Control statements AMU
cout << "FIRE!";
return 0;
}
More examples
Program to accept 10 numbers and to add only the positive neglecting the negative
numbers
// to add only +ve numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n, sum=0;
cout<<"enter any 11 numbers\n";
for (i=0; i<=10; i++)
{
cin>>n;
if (n<0)
continue;
sum += n;
}
cout << " sum of +ve numbers = "<<sum;
getch();
}
//Read sides of triangle and find right angle or not.
#include<iostream.h>
#include<conio.h>
void main()
{
int a, b, c;
char ch;
cout<<"enter three sides ";
cin>>a>>b>>c;
For G1 Computer science students (2014) Page 14 of 16
Chapter 4 – Control statements AMU
if(a>b && a>c)
ch='a';
else
if(b>a && b>c)
ch='b';
else
ch='c';
switch (ch)
{
case 'a':
if((a*a)==(b*b+c*c))
cout<<"a right angle triangle ";
else
cout<<"not";
break;
case 'b':
if((b*b)==(a*a+c*c))
cout<<"b right angle triangle ";
else
cout<<"not";
break;
case 'c':
if((c*c)==(b*b+a*a))
cout<<"c right angle triangle ";
else
cout<<"c is not a right angle triangle";
break;
}
}
//program to print a
pyramid
#include<iostream.h>
#include<conio.h>
void main()
For G1 Computer science students (2014) Page 15 of 16
Chapter 4 – Control statements AMU
{
int n,i,j;
cout<<"enter n ";
cin>>n;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
cout<<"* ";
cout<<"\n";
}
}
output:
enter n 5
*
**
***
****
* * * * * */
/* Program to find the first n prime
sum++;
numbers.*/
break;
#include<iostream.h>
}
#include<conio.h>
if (sum==0)
void main()
{
{
count++;
int n,j,sum=0,count=0;
cout<<k<<" ";
unsigned long int k;
}
cout<<"enter n ";
if(count==n)
cin>>n;
break;
for(k=2;k<=4294967295;k++)
}
{
getch();
sum=0;
}
for(j=2;j<=k/2;j++)
Output
if ((k%j)==0)
enter n 9
{
2 3 5 7 11 13 17 19 23 *
For G1 Computer science students (2014) Page 16 of 16