Chapter 10 Control Statements
Chapter 10 Control Statements
eÁw
CHAPTER 10
Control Statements
OBJECTIVES
To Understand the various control statements
Usage
Implementation
199
200
Control Statements
10.1 Introduction
A program
eÁw is usually not limited to a sequence of instructions. During its process it may bifurcate,
repeat or take decisions. For that cause, C++ provides us control structures, statements that can alter
the flow of a sequence of instructions. In C++program, statements are executed sequentially in the order
in which they are written. Such programs are called as sequential structures.
With the introduction of control structures we are going to introduce a new concept calledcompound
statement or block. Block is a group of statements which are separated by semicolons ( ; ) like all C++
Statements, but grouped together in a block enclosed in braces { and };
Most of the control structures that we will see in this chapter require syntax. A statement can be a
simple statement or compound statement. The order of execution of statements may be changed depending
on certain conditions to make a proper decision.
The order in which statements are executed in a program is called flow of control. C++ provides
control structures that serve to specify what has to be done by the program, when and under what
circumstances.
Control statements are statements that alter the sequence of flow of instructions.
Any single input statement, assignment and output statement is simple statement.
A group of statements that are separated by semicolon and enclosed within curled braces {and}
is called a block or compound statement.
201
Control Statements
10.3.1 if statement
This is the simplest form of if statement. This statement is also called as one-way branching.
This statement is used to decide whether a statement or a set of statements should be executed or not.
The decision is based on a condition which can be evaluated to TRUE or FALSE.
The general form ofif statement is
if (condition) if (condition)
OR {
statement1
; statement-1;
statement-2;
…….
statement-n;
}
Is F Is F
condition? condition?
T T
Statement-1 statement-1
statement-2
-------
Next statement statement-n
next-statement
202
Control Statements
203
Control Statements
Program 10.2 To findthe largest, smallest and second largest of three numbers
usingsimple if statement.
#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) Program
{
int a, b, c, largest, seclargest, smallest ;
clrscr( );
cout<< " Enter three numbers: ";
cin>> a>>b>>c;
largest = a;
smallest = a;
if ( b > largest)
largest = b;
if (c > largest)
largest = c;
if ( b < smallest)
smallest = b;
if (c < smallest)
smallest = c;
seclargest = (a+b+c) - (largest + smallest);
cout<<"Largest number is " << largest<<endl;
cout<<"Second largest number is " <<seclargest<<endl;
cout<<"Smallest number is " << smallest<<endl;
getch( );
}
204
Control Statements
Program10.3Input the total amount in a bill, if the amount is greater than 1000, the
eÁw discount of 8% is given. Otherwise, no discount is given. Output the total
amount, the discount and the final amount.
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ Program
float amount, discount, netdiscount, netamount;
clrscr( );
cout<< "Enter amount: ";
cin>>amount;
discount = 0.0;
if (amount >= 1000)
discount = 8/100;
netdiscount = amount * discount;
netamount = amount – netdiscount;
cout<<”Net discount = “<<netdiscount<<endl;
cout<<”Net amount = “<<netamount<<endl;
getch();
}
205
Control Statements
if (condition )
statement1;
else
statement2;
If the given condition is TRUE then statement1 will be executed. Otherwise statement2 will be
executed.
Only the code associated with if or the code associated with else will be executed, never both.
Both statement1andstatement2may be single or compound statements.
It is important to note that after executing either statement1 or statement2, the compiler control
goes to the next statement in the program.
206
Control Statements
207
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ Program
int year;
clrscr( );
cout<< " Enter the year: ";
cin>> year;
if ( year%4 == 0 && year%100!= 0 || year%400 == 0 )
cout<<"It is a leap year"<<endl;
else
cout<<"It is not leap year"<<endl;
getch( );
}
208
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) Program
{
char ch;
clrscr( );
cout<< " Enter the character: ";
cin>>ch;
if ( ch>=’A’ &&ch<=’Z’)
cout<<"It is an upper-case character"<<endl;
else
cout<<"It is a lower-case character"<<endl;
getch( );
}
209
Control Statements
if (condition1 )
statement1;
else
if (condition2)
statement 2;
else
-------------
else
if(condition-n)
statementn;
else
defaultstatement;
T F
Is
condition1?
1
statement1 T F
Is
condition1?
1
statement2
T F
Is
condition-n?
statementn defaultstatement
First condition1 is tested. If condition1 is TRUE then statement1 is executed. Otherwise, condition2
is tested. If condition2 is TRUE then statement2 is executed. Otherwise, condition3 is tested and so on.
Finally, condition-n is tested. If it is TRUE, statement-n is executed. If none of the conditions is TRUE
then default statement is executed.
210
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int marks;
clrscr();
cout<< "Enter marks: ";
cin>>marks;
if ( marks >= 85 && marks <= 100 )
cout<<”Distinction”<<endl;
else
if ( marks >= 60 )
cout<<”First class”<<endl;
else
if ( marks >= 50)
cout<<”Second class”<<endl;
else
if ( marks >= 35)
cout<<”Pass class”<<endl;
else
cout<<”Fail”<<endl;
getch();
}
211
Control Statements
Format II:
. This structure contains an if-else statement within another if-else statement.
The general form of if- else-if statement is
if (condition1 )
if (condition2)
statement1;
else
statement2;
else
if(condition3)
statement3;
else
statement4;
F T
Is
condition1?
F T F T
Is Is
condition3? condition2?
212
Control Statements
213
Control Statements
Is
expression
This statement checks the values of the variable or expression given within the parenthesis with a list
of case constants.
Each case value must be unique within a switch statement.
After the word case, a space is given then label or constant is to be written followed by
colon (:).
All cases must be enclosed with in curled braces.
While executing, depending on the label/constant, the corresponding set of statements are executed.
If the value of the expression is not matched with label/constant then default statement is executed.
Every case must consist of break statement to terminate corresponding cases. Otherwise, the
following statements are executed until break is encountered.
214
Control Statements
Program
eÁw 10.10Program todisplay a day number in a week using switch statement
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int dayno;
clrscr();
cout<< “Enter day number of the week: “;
cin>>dayno;
switch(dayno )
{
case 1 : cout<< “SUNDAY ”<<endl;
break;
case 2 : cout<< “MONDAY”<<endl;
break;
case 3 : cout<< “TUESDAY ”<<endl;
break;
case 4 : cout<< “WEDNESDAY”<<endl;
break;
case 5 : cout<< “THURSDAY”<<endl;
break;
case 6 : cout<< “FRIDAY ”<<endl;
break;
case 7 : cout<<“SATURDAY”<<endl;
break;
default : cout<< “ Invalid day number ”<<endl;
break;
}
getch();
}
215
Control Statements
The switch statement is a bit peculiar within the C++ language because it uses labels instead
of blocks. This forces us to put break statements after the group of statements that we want to execute
for a specific condition. Otherwise the remainder statements including those corresponding to
other labels will also be executed until the end of the switch selective block or a break statement is
reached.
For example, if we do not include a break statement after the first group of case one, the program
will not automatically jump to the end of the switch statement and it would continue executing the rest of
statements until it reaches either a break instruction or the end of the switch statement. This makes it
unnecessary to include braces { and} surrounding the statements for each of the cases.
216
Control Statements
eÁw
217
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n;
clrscr();
cout<< "Enter the starting number: ";
cin>> n ;
while ( n > 0 )
{
cout<<setw(4)<<n ;
--n;
}
cout<< " end of loop \n ";
getch();
}
When creating a while-loop, one must always consider that it has to end at some point, therefore we
must provide within the block some method to force the condition become FALSE at some point, and
otherwise the loop will continue looping forever. This case is called as infinite loop.
218
Control Statements
219
Control Statements
Program 10.13To find the compound interest given amount, rate of interest and time
#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) program
{
float priamt, netamt, rate, ci;
int time, year;
clrscr();
cout<< "Enter the principal amount, rate of interest and time: "<<endl;
cin>>priamt>>rate>>time;
netamt = priamt;
year = 1;
while ( year <= time )
{
netamt = netamt*(1+rate/100);
year++;
}
ci = netamt - priamt;
cout<<"Compound interest = "<<ci<<endl;
cout<< "Nett amount = "<<netamt<<endl;
getch();
}
Sample run: Enter the principal amount, rate of interest and time:
1000 10 5
Compound interest = 610.51
Nett amount = 1610.51
220
Control Statements
do do
{ {
statement 1; statement 1;
} while ( test-condition ); OR statement 2;
…….
statement-n;
} while ( test-condition );
statement1 statement1
statement2
T Is OR
condition?
n
F
nextStatemen statementn
t1
T
f Is
condition?
F
f
Although the curly braces are not necessity when only one statement is present, they are usually
used to avoid confusion. The do-while loop iterates until condition becomes FALSE.
221
Control Statements
Program 10.14 To print all even numbers from 1 to 25 using do-while loop
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int i;
clrscr();
i = 2;
do
{
cout<<setw(4)<<i ;
i = i+2;
}while ( i <= 25);
getch();
}
Sample Run : 2 4 6 8 10 12 14 16 18 20 22 24
#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) program
{
int n, sum, num, digit ;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
num = n;
sum = 0;
do
{
digit = num%10;
sum = sum+digit*digit*digit;
n = n/10;
}while (n != 0);
if (sum == num)
cout<<”It is an Armstrong number”<<endl;
else
cout<<”It is not an Armstrong number”<<endl;
getch();
}
222
Control Statements
If the number can be expressed as the sum of cube of its digits, the number is called an Armstrong
number.
while do-while
223
Control Statements
for counter = IV to FV
statement1
statement2
……..
statementn
NEXT
counter
The initialization is as n assignment statement that is used to set the loop control variable.
The condition is a relation a relational expression that determines when the loop exits.
The increment/decrement defines how the loop-control variables changes each time the loop
is repeated.
You must separate these three major sections by semicolon.
This for loop continues to execute as long as the condition is TRUE. Once the condition
becomes FALSE, the program execution continues on the statement following for structure.
224
Control Statements
For loop allow two initialization statements. It is one of the most common variations that
useseÁw
the comma operator to allow two or more variables to control the loop.
Its main function is to repeat the execution of statements while condition remains TRUE, like the
while loop. But in addition, the for loop provides specific locations to contain an initialization statement
and an increment/decrement statement. So this loop is specially designed to perform a repetitive action
with a counter which is initialized and increased/decreased on each iteration.
This looping structure works as follows.
1. Initialization is executed. Generally it is an initial value setting for a counter variable and is ex-
ecuted only one time.
2. Condition is checked. If it is TRUE the loop continues, otherwise the loop ends and control
exits from for structure.
3. Statement is executed as usual, it can be either a single statement or a block enclosed in curled
braces { and}.
4. At last, whatever is specified in the increase field is executed and the loop gets back to execute
step 2.
5 The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon sign between them must be written compulsorily.
6 Optionally, using the comma operator we can specify more than one expression in any of the
fields included in a for loop.
Program 10.16 To print all the odd numbers upto the given limit
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i ;
clrscr();
cout<<”Enter the limit: “<<endl;
cin>>n;
for (i=1; i<=n; i=i+2)
cout<<setw(4)<<i;
getch();
}
225
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int n,fact, i ;
clrscr();
cout<<”Enter the number: “;
cin>>n;
fact = 1;
for (i=1; i<=n; i++)
fact = fact * i;
cout<<n<<”! = “<<fact;
getch();
}
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n,i ;
clrscr();
cout<<”Enter the number: “;
cin>>n;
cout<<”The integer divisors are “<<endl;
for (i=2; i<=n/2; i++)
if (n% i == 0)
cout<<setw(5)<<i;
getch();
}
226
Control Statements
All these can be done by using break, exit, and continue statements.
Above program segment prints the numbers 0 through 10 on the screen. Then the
loop terminates because break causes immediate exit from the loop, overriding the conditional test
n < 100.
227
Control Statements
Program 10.19 To test whether a given number is prime or not using break statement.
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i, status;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
status = 1;
for(i=2 ; i <=n/2; i++)
{
if(n % i == 0)
{
status = 0;
cout<<”It is not a prime “<<endl;
break;
}
}
if(status)
cout<< “ It is a Prime Number”;
getch();
}
228
Control Statements
The return code is used by some operating systems and may be used by calling programs. By
convention,
eÁw
an exit code of 0 means that the program finished normally and any other value means that
some error or unexpected results happened.
Program 10.19 To test whether a given number is prime or not. Using exit( ) function
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
for(i=2 ; i <=n/2; ++ i)
if(n % i == 0)
{
cout<<”It is not a prime “<<endl;
exit(0);
}
229
Control Statements
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n;
clrscr();
for( n = 10; n > 0; n-- )
{
if ( n == 5 ) continue;
cout<<setw(5)<< n ;
}
cout<< “ END OF COUNT \n “ ;
getch();
}
statement1;
statement2;
gotolabel_name;
statement3;
statement4;
label_name: statement5;
statement6;
230
Control Statements
loop: cout<<setw(5)<< n;
n--;
if ( n > 0 ) goto loop;
cout<< “END OF LOOP“ ;
getch();
}
231
Control Statements
232
Control Statements
31. Write a for loop that display the numbers from 50 to 61.
32. Name the jump statements provided by C++.
33. What is purpose of break statement?
34. Why is the continue statement used?
35. What is the function of exit( ) ?
36. Which header file must be included in the program for using the exit( )function?.
233
Control Statements
234
Control Statements
11. Write a program to find the sum occurrence of a digit of a given number using do while.
12.eÁw Write a program to find all the integer divisors of a given number using for loop.
13. Write a program to find factorial of a given number using for loop.
14. Write a program to print Fibonacci series using for loop.
15. Write a program to find sum of the series s = 1+x+x2+…………+xn using for loop.
235
236