0% found this document useful (0 votes)
14 views

Chapter 10 Control Statements

The document discusses control statements in C++. It describes selection statements like if and if-else statements which allow altering the flow of a program based on certain conditions being true or false. It also briefly introduces iteration statements. Example programs demonstrate using if and if-else statements to find the largest of numbers, determine if a shape is a square or rectangle, and provide discounts.

Uploaded by

tanisharavind777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter 10 Control Statements

The document discusses control statements in C++. It describes selection statements like if and if-else statements which allow altering the flow of a program based on certain conditions being true or false. It also briefly introduces iteration statements. Example programs demonstrate using if and if-else statements to find the largest of numbers, determine if a shape is a square or rectangle, and provide discounts.

Uploaded by

tanisharavind777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

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.

10.2 Types of control statements


C++ supports two basic control statements.
 Selection statements
 Iteration statements

10.3 Selection statements


This statement allows us to select a statement or set of statements for execution based on some
condition.
The different selection statements are:
i. if statement
ii. if-else statement
iii. Nested statement
iv. switch 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

In the above syntax


 The condition gives 0 (FALSE) or 1 (TRUE).
 If the condition is true, it has value1 and statement-1 is executed.
 If the condition is false, it has value 0 and statement-1 is not executed.
 The expression (or condition) must be put inside the parentheses.
 statement-1 will be executed only when the condition is true (some time it may be block of
statements).
 If the condition is false then control skips statement-1 and executes next the statement in the
program. i.e., statement-2

Example 10.1 if ( n = = 100)


cout<< “ n is 100 “;

202
Control Statements

Program 10.1 To find largest of two numbers using if statement


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b, large;
clrscr();
cout<< “ Enter two numbers: “;
cin>> a>>b;
large = a;
if ( b > large )
large = b;
cout<<”Largest number is ” << large;
getch( );
}

Sample run: Enter two numbers


20 10
Largest number is 20

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( );
}

Sample run: Enter three numbers: 10 50 30


Largest number is 50
Second largest number is 30
Smallest number is 10

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();
}

Sample run: Enter amount: 2000


Net discount = 160
Net amount = 1840

205
Control Statements

10.3.2 The if–else statement


This statement is also called as two-way branching. It is used when there are alternative statements
need to be executed based on the condition. It executes some set of statements when the given condition
is TRUE and if the condition is FALSE then other set of statements to be executed.
The general form of if- else statement is.

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

Program 10.4 To determine whether the shape is square or rectangle


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int breadth, height;
clrscr();
cout<< "Enter value of breadth and height : ";
cin>> breadth>>height;
if ( breadth == height )
cout<< "It is a square ….";
else
cout<< "It is a rectangle ….";
getch();
}

Sample run: Enter value of breadth and height : 5 5


It is a square ….
Sample run: Enter value of breadth and height : 5 10
It is a rectangle ….

207
Control Statements

Program 10.5 To find greatest of two numbers


#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b;
clrscr();
cout<< "Enter two numbers: ";
cin>> a>>b;
if ( a>b )
cout<<a<<" is the greatest … .";
else
cout<<b<<" is the greatest ….";
getch();
}

Sample run: Enter two numbers: -10 10


10 is the greatest

Program 10.6 To determine whether the year is a leap year

#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( );
}

Sample run: Enter the year: 2012


It is a leap year
Sample run: Enter the year: 1900
It is not leap year

208
Control Statements

Leap year program


A leap
eÁw year is a year in which one extra day (February 29) is added to the regular calendar. Most of
us know that the leap years are the years that are divisible by 4. For example, 1992 and 1996 are leap
years. There is an exception to this rule: centennial years are not leap years. For example, 1800 and 1900
are not leap years. But, there is exception to the exception: centennial years that are divisible by 400 are
leap years. Thus, year 2000 is a leap year.

Program 10.7 To determine whether the input character is lower-case or upper-case

#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( );
}

Sample run: Enter the character: G


It is an upper-case character
Sample run: Enter the character: j
It is a lower-case character

10.3.3 Nested-if statement


If the statement of an if statement is another if statement then such an if statement is called as nested
if statement. Nested-if statement contains an if statement within another if statement.
There are two forms of nested if statements

Format I: if-else-if statement


This structure is also called as else-if ladder. This structure will be used to verify a range of values.
This statement allows a choice to be made between different possible alternatives. A choice must be
made between more than two possibilities.

209
Control Statements

The general form of if- else-if statement is

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

Program to declare the result based on the following rules:


eÁw
Marks Grade
85 – 100 Distinction
60 – 84 First class
50 – 63 Second class
35 – 49 Pass class
0 – 34 Fail

Program 10.8 To find grade of the student

#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();
}

Sample run: Enter marks: 71


First class
Sample run: Enter marks: 32
Fail

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?

statement4 statement3 statement2 statement1


2

212
Control Statements

Program 10.9 To find the greatest of three numbers


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b, c;
clrscr();
cout<< "Enter three numbers: ";
cin>>a>>b>>c;
if(a>b)
if (a>c)
cout<<a<<” is the greatest”<<endl;
else
cout<<c<<” is the greatest”<<endl;
else
if (b>c)
cout<<b<<” is the greatest”<<endl;
else
cout<<c<<” is the greatest”<<endl;
getch();
}

Sample run: Enter three numbers: 10 20 30


30 is the greatest
Sample run: Enter three numbers: 10 30 20
30 is the greatest
Sample run: Enter three numbers: 30 10 20
30 is the greatest

10.3.4 switch statement


C++ has a built-in multiple-branch selection statement, switch. This successively tests the value of
an expression against a list of integer or character constants. When a match is found, the statements
associated with that constant are executed.

213
Control Statements

The general form is


switch (Expression)
{
case label-1: statement-1;
break;
case label-2: statement-2;
break;
………
case label-n: statement-n;
break;
default : default-statement;
}

Is
expression

=label-1? =label-2? =label-n? default

statement-1 statement-2 statement-n default-statement

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();
}

Sample run: Enter day number of the week: 5


THURSDAY
Sample run: Enter day number of the week: 10
Invalid day number

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.

10.4 Iteration statements or loops


Iteration statements are also called as loops. Loop is a statement that allows repeated execution of
a set of instructions certain condition is satisfied. This condition may be predefined or post-defined.
Loops have a purpose to repeat a statement or set of statements a certain number of times or while a
condition is fulfilled. We use three types of looping structures in C++.
 while loop
 do- while loop
 for loop

10.4.1 while loop


This looping structure is also called as pre-tested looping structure. This statement repeats the
execution of a set of statements while the condition is TRUE.
The general form of while loop is

while (test-condition ) while ( test-condition)


statement1; OR {
statement 1;
statement 2;
………
statement n;
}

216
Control Statements

eÁw

This looping structure works as follows:


i. The condition is tested.
ii. If the condition is TRUE, the statement or set of statements inside the loop are executed.
iii. The condition is tested again.
iv. The process is repeated until the condition becomes FALSE.
v. When the condition becomes FALSE, control goes to the next statement of the loop.

217
Control Statements

Program 10.11 To print numbers in descending order

#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();
}

Sample run: Enter the starting number: 10


10 9 8 7 6 5 4 3 2 1 end of loop

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

Program 10.12 To find sum of digits in a given number


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int n, sum=0, digit ;
clrscr();
cout<< "Enter the number: ";
cin>> n ;
while ( n != 0 )
{
digit = n%10;
sum = sum+digit;
n = n/10;
}
cout<< "Sum of digits = "<<sum<<endl;
getch();
}

Sample run: Enter the number: 7039


Sum of digits = 19

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

10.4.1 do-while loop


This
eÁwlooping structure is also called as post-tested looping structure. Unlike while loop that test
the loop condition at the beginning, the do-while loop checks the condition after the execution of the
statement. This means that a do-while loop always executes at least once. Its functionality is exactly the
same as the while loop, except that the condition in the do while loop is evaluated after the execution of
statement, instead of before.
The general form of the while loop is:

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

Program 10.15 To determine whether the given number is an Armstrong number

#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

Sample Run :Enter the number: 153


eÁw
It is an Armstrong number

Sample Run :Enter the number: 175


It is not an Armstrong number

If the number can be expressed as the sum of cube of its digits, the number is called an Armstrong
number.

10.4.3 Comparison of while and do-while statements

while do-while

 It is a pre-tested looping structure.  It is a post-tested looping


 It tests the given condition at initial structure.
pint of looping structure  It tests the given condition at the
 If given condition is TRUE then last of looping structure.
body of the loop will be executed  If the given condition is TRUE
again and again. then body of the loop will be
 If the condition becomes FALSE, executed again and again.
controller will comes out of loop  If the condition becomes FALSE,
and executes next set of statements controller will comes out of loop
 If condition is FALSE, it will not and executes next set of statements
allow controller to execute the  Even the condition is FALSE at
statements. initial point, then also this loop
 The statements may not be executes statements once, then
executed even once. terminates it.
 while(test_condition)  The statements are executed atleast
{ once.
statement1;  do
statement2; {
: statement1;
: statement2;
statementn; ------
} statement;
} while(test_condition);

223
Control Statements

10.4.4 The for loop


This statement is called as the fixed execution looping statement. It is normally used when we
know in advance exactly how many times a set of statements should be repeatedly executed again and
again. It provides initialization, loop-end-condition and increment/decrement process statements in a single
line. When one is aware of fixed number of iterations, then this looping structure is best suited.
The general form of for statement is

for ( initialization ; condition ; increment/decrement)


{
statement1;
statement2;
……..
statement;
}

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.

For example, for( x=0, y=0; x+y<10; ++y)

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();
}

Sample Run : Enter the limit: 25


1 3 5 7 9 11 13 15 17 19 21 23 25

225
Control Statements

Program 10.17 To find the factorial of a given number

#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();
}

Sample Run : Enter the number: 7


7! = 5040

Program 10.18 Tofind all the integer divisors of a number

#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();
}

Sample Run : Enter the number: 108


The integer divisors are
2 3 4 6 9 12 18 27 36 54

226
Control Statements

10.5 Jump statements or Transfer of control from within loop


Transfer
eÁw of control within looping are used to
 Terminate the execution of loop
 Exiting a loop
 Half way through to skip the loop.

All these can be done by using break, exit, and continue statements.

10.5.1 break statement


The break statement has two uses. You can use it to terminate a case in the switch statement. And
you can also uses it to force immediate termination of a loop like, while, do-while and for, by passing the
normal loop conditional test. When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next statement.
The general format of break statement is:
break;

Example 10.5 for( n = 0; n < 100; n++ )


{
cout<< n;
if ( n ==10 ) break;
}

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();
}

Sample Run : Enter the number: 53


It is a Prime Number

Sample Run : Enter the number: 49


It is not a prime

10.5.2 exit( ) function


Just as you can break out of a loop, you can break out of a program by using the standard library
function exit( ). This function causes immediate termination of the entire program, forcing a return to the
operating system. In effect, the exit( ) function acts as if it were breaking out of the entire program.
The general form of the exit( ) function is:
exit ( ); OR void exit ( int return _code);

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);
}

cout<< “It is a Prime Number”;


getch();
}

Sample Run : Enter the number: 17


It is a Prime Number

Sample Run : Enter the number: 25


It is not a prime

10.5.2 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.
The continue statement works somewhat like break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any code in
between.
The general form of the continue statement is:
continue;

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();
}

Sample Run :10 9 8 7 6 4 3 2 1 END OF COUNT

10.5.3 goto statement


The goto allows to make an absolute jump to another point in the program. This statement
execution causes an unconditional jump or transfer of control from one statement to the other
statement with in a program ignoring any type of 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 ( : )
The general format of goto statement is:

statement1;
statement2;
gotolabel_name;
statement3;
statement4;
label_name: statement5;
statement6;

230
Control Statements

Program 10.21Program to print numbers from 10 to 1 usinggoto statement


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n = 10;

loop: cout<<setw(5)<< n;
n--;
if ( n > 0 ) goto loop;
cout<< “END OF LOOP“ ;
getch();
}

Sample Run :10 9 8 7 6 5 4 3 2 1END OF LOOP

231
Control Statements

One mark questions:


1. What is compound statement?
2. What is block?
3. Name the types of control statements.
4. What are the three different constructs?
5. What is selection statement?
6. What is iterative statement?
7. What is the numerical equivalent of TRUE and FALSE?
8. Which selection statements does C++ provide?
9. What are the rules associated with if statement?
10. What is the purpose of else clause?
11. What is two way branching statement?
12. Correct the following code fragment:
if( x = 1 )
k = 100;
else
k = 10;

13. Consider the following program segment.


x = 10; y = 5;
if ( x > y) w = 15;
w = 25
cout<< " value of w is ";
cout<< w;
find the output.

14. What will be the output of the following code fragment?


;
cin>>a;
if( a == 50 )
cout<< “ FIFTY “;
else
cout<< “ NOT FIFTY “;
If the input given is i. 70 ii. 50, what is the output?

232
Control Statements

14. What will be the output of the following code fragment?


eÁw ;
int year;
cin>> year;
if ( year % 100 == 0)
if ( year % 400 == 0)
cout<< “ LEAP “;
else
cout<< “ NOT CENTURY YEAR “;

if the input given is i. 2000. ii. 1900. iii. 1971. ?

15. State the use of nested if statement.


16. What is the purpose of switch statement?
17. How does the switch statement differ from if statement.
18. What type of value can be taken by case labels?
19. What is the significance of default clause in a switch statement?
20. Define the term looping.
21. Name the iteration statements provided by C++.
22. When should we use while and do while loop?
23. What is pre-tested looping structure?
24. What is post-tested looping structure?
25. Write a program fragment to display numbers 2, 4, 6, 8, 10, ………..18, 20.
Using while loop.
26. Write a program fragment to display numbers 1,3,5,7,9,………….17,19.
Using do while loop.
27. Which structure is called as fixed-execution looping statement?
28. When should we use for loop?
29. What is the output of the following code fragment?
for ( int i = 1; i< 10; i ++ )
cout<< i;
30. Why does “ Hellow” not print even once ?
for ( i = 0 ; i > 10 ; i ++ )
cout<< “ Hellow “;

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

Two marks questions:


1. What is the purpose of if – else statement?
2. What are the nested statements?
3. Write syntax of if- else statement.
4. What is the purpose of switch statement?
5. What are the case labels? What type of labels must be used in case labels?
6. What will be the output of following code when i. ’A’ ii. ‘C’. iii. ’D’. iv. ‘F’.
cin>> choice;
switch(choice)
{
case ‘A’ :cout<<“ GRADE A \n”;
case ‘B’ : cout<< “ GRADE B \n”;
case ‘C’ : cout<< “GRADE C \n”;
break;
case ‘D’ : cout<< GRADE D \n”;
default: cout<< GRADE F \n”;
}

7. Explain the syntax of the while loop with a suitable example.


8. Explain working of do while loop with an example.
9. Compare the working of while and do while loop.
10. Write a short program using while to print 14710………. 40.
11. Write a program segment using do while to print all odd numbers from 1 to 24
12. Write a short program to find largest of three numbers.
13. Write a short program to test the given number is even or odd.
14. Explain the syntax of for loop with a suitable example.
15. Compare break and continue statements.
16. Write the function of goto statement with general format.

Five marks questions:


1. Explain the working of if statement and if else statement with suitable program fragments.
2. Explain if else if statement with general format and suitable example.
3. Explain the working of switch statement with an example.
4. Write general format of while loop with a suitable programming example.
5. Explain working of do while statement with an example.
6. Write a program to find the sum of the series 1+1/3!+1/5!+…….1/n! using while loop.
7. Differentiate between while looping with do while looping structure
8. Explain working of for looping structure with a programming example.
9. Write a program to find sum of digits of a given number using while loop
10. Write a program to find GCD of two numbers using while loop

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

You might also like