0% found this document useful (0 votes)
22 views23 pages

Control Statements

Uploaded by

sahilsalaria2617
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views23 pages

Control Statements

Uploaded by

sahilsalaria2617
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

6

Control Statements-
6 . 1 . INTRODUCTION

statement
a it runs sequentially top to bottom executing every
Generally, when we run program, C language also
once. By detault, this is how control flows in a program.
and on its exactly way
C allows us to
sequentially.
bottom However,
mits us to alter the default behavior fromoftop to irrelevant
or more statement (or group statements) multiple times and skip the
execute one
are used in C language, which
are known as control
do To various
so, statements
statement(s) also.
of the program ie.
statements.

statements control the flow


Control statements are called so because these
and how many times.
statements of a program will execute (or will not execute)
when and which Flow of Control" in a program, are
called
those statements of C, which control the
More technically,
Control statements.

control statements, these are


There are three categories of these
1. Branching Statements

Jumping Statements
3. Looping Statements
in C is given next.
statements
Diagram of various control
Control Statements in C

looping statements
jumping statements
branching statements

entry controlled exit controlled


break continue return
f statement switch statement goto

while do while
for
else if ladder
Simple if if-else nested if-else
Statements in C
6.1. Diagram of Control
Fig.
statements available in
C. We will discuss each of
are various
control
then
OW in above diagram which will be dealt with
return statement,
in Functions.
etail in this chapter except of statements enclosed in pair of curly braces is
all. important to know that in C, any group statements, we make use of compound statement
control
When we use
mpound statement,
very
very much. 105
Control Statem
BRANCHING STATEMENTS OR
6.3. BRANCH

cONDITIONAL
uopose,
Let us suppose
CONTROL
we
STATEMENTS
SELECTION STATEMENTS
want to
STATEMENTS OR
find the result
Firs
Purther,
Year Further, suppoc
suppose minimum
of a
student
passing marks is 40%. the
on
basis of
First
ined by student is greater than
m a r k so b t a i n e d a
So we needpercentage ained in B
display the result
result as "Pass"o
"Passas
or
otherwIe, if marksequal to 40 then he/she to verify, percentage
verify, if
percentag of
has passed
disple Calculation dependent on the
ole calculation is depend are less than 40% we will
the exam and
we w
lessA2
his
than 400% Such problems can be conditions like if marks display the resut "Fa
solved in C percentage is 40% or more or 1s
the hand, we may need to
other hand,
On the other
make some
language using branching statements.
T

of of statements, which one


or group
state
(and decision too, like out of two or
e only one) should be more different set
statements. These statements help
branching statements.
executed. Por this
purpose, we u
rerent
like branches of aa tree,
differenm branches tree,
forming
a
programmer to create set of
different statements, which behave
ifically, branching statements are used paths that may be followed
More specifically, at any decision
more alternatives available.
for
decision-making to select point.
one out of two or
There are two subcategories of branching statements.
1,if statement (if statement itself is of four These are:
(a) simple if statement subtypes).
(b) if-else statement
(c) nested if-else statement
d) else-if ladder
2. switch statement

6.3.1.simple if statement
simple if statement is used when there is need to make some decision
based on some condition(s).
Very simply, simple if allows the program to execute one or more
ifa certain condition is met. statements a of (or block code) only

Simple if statement is called a branching statement because it


program has to select one of two given provides a junction where the
paths.
It allows conditional
execution of a single block of code, depending on the result of a condition.
However, that is all it does. There is no alternate behavior when the
ms 1s expression evaluates to false.
shortcoming of simple if statement and that is why its use is limited. (To get such behavior, we
S e the else
statement, which executes a certain block of code in case the condition inside if
tatement is false.)
he Syntax or General Format or Structure of simple if statement is
if(Some Condition)
group of statements called true part ofif statement *

statement-x i.e. remaining part of the program */


relational or logical expression
some
arithmetic,
w a s some ar hi
is generally Even if c o n d i t i o n
o r false. wherenetje
Some_Condition
either true false
Where,
will be the rule that O is reas every
its result C follows
value, then
evaluated:
condition is
in 0
non-zero

result or
expression
that can

is True.
written
within pair of curly braces
curlv

other n u m e r i c
value
group
of
statements

is false then true


part na o
is True then condition

If output of
condition
e x e c u t e d and
if output
of
of the program, if a it
if s t a t e m e n t ) is remaining part
i.e. any.
(called true part of to
statement-x
and execute a gro
and control jumps conditionaly
select

s t a t e m e n t used fo
statement is skipped programmer
to
statement helps the and a n if this
simple if
statement
Thus decision-making
called
statements.
That is why it is
termed as branching.
objective is above if statement
Part of p r o g r a m

Evaluate False
condition/expression

True

True part of if
i.e. body of it

below if statement
Part of Program
if statement
Fig. 6.2. Flow chart of true
are known as
and } (compound statement)
Here, statements written
inside curly braces{ if there is single statement
statement has a single statement i.e.
part of ifstatement, if this compound
braces can be omitted.
inside curly braces then pair of curly
6.3.1.1. Imporlant poinis about if statement written n

lower (Note, all keywords of C are


keyword of C and is written in
case.
TIs

lower case e.g. main( ), while etc.)


There is no semicolon (:) after if(Some_Condition) u

relational expression, is written in parenthesis( ), neither


SomeCondition, which is mostly a
curly braces {} nor in square brackets[ ] t
Comparison is performed using == called comparison operator and not using assig
ntrol
operalor A very common mistake performed by students in if statements and other cOnu
Such
SLatements is the accidental use of non-relational statements as the conditional expressio,
as, Doing
use
of the assignment operator =
instead of the equality comparison operator
S0, Completely changes the meaning of if statement. For example, if(a=0) will always i esult
in false, if(a=2) which is non-zero and will always result in true and if ult i
108 (2=a) Will re
tax error (Lvalue required) because we cannot use constant on left side of assignment
syntax eTor

o p e r a t o r .

there is si
single statement inside
In case curly braces, then curly braces are not mandatory.
ample of simple if statement follows
A ne x a m p l e next.
m6.1.
Program6. To check if sa number given by user is even.

main)

intnum
printf"nPls enter a number: ");
sCanf%d", &num); g e t a number from user */
ifnum%2==0) /* find remainder when number is divided by 2*/

printf(Its Even."); Output:


Pls enter a number: 16
Its Even.
FxDlanation. Program asks user to enter a number and stores the number in variable num, then
divided
isdivided by
by.2 and remainder is find using remainder operator %, then using simple if statement
rwminderis compared with 0, if expression within if statement i.e. num%2= 0 is true then programn
outputs the message "Its Even".
ifstatement in this program, written as if (num 62=0) can also be written as if(!(num%2)),!
isalogical NOT operator and will turn the result zero provided by num%2 to 1, and in C, any non-
ero number means True (Zero means False).

NOTE
There is one limitation of above program, if number is noteven then
program does not display
any message, this problem will be solved using if-else statement

Try Yourself
Program to check is a given number divisible by 5.
Program to check is a give number less than equal to 100.
332. if-else statement (adding else to simple if statement)
ie Statement is a
ISe
two-way branching statement which implies do one thing or the other. So
aement is used when there are two alternatives available, first if the condition is true and
Ach e condition is false. Compare this with simple if statement (explained in previous section)
whi
it has only one group of statements to execute if condition is true, i.e. we have only, true part of
t.But Se we have two parts, true part of if which is group or block of statements to be executed
cond rue and a false part of if which is another group or block of statements to be executed
tcon
f
condition is false.
Control Statements
109
The Syntax or General Format or Structure of if-else is
if(Some Condition)

group of statements (or control statement) called true part of if/


true *
this block or group is executed when condition is

else

called false
part of if*/
group of statements (or control statement)
*/
this block or group is executed when condition is false

part of program below if-else statement"/


Part of program above if statement

Evaluate False
Condition/expression
True

True part of if False part of if


i.e. body of if |i.e. body of else

Part of Program below if-else statement


Fig. 6.3. Flowchart of if-else statement
Again, condition is evaluated as true or false. If it outputs as true, first group of statements
called true part of if is executed, and if condition is evaluated as false then second group of statemens
called false part of if is executed.
Whenever if-else is used then exactly one of these two parts is
it will happen that both parts are skipped, nor it will
surely executed. It means, neluc
happen that both are executed.
6.3.2.1. Important points about if-else
. Like simple if, here also there is no semicolon
() after if(Some_Condition)
if and else are
keywords of C and are written in lower case
ifkeyword is followed by some condition (written using a
expression), and no condition is required with else. arithmetic/relational/logn
True part and false part statements are written separately in { } and are called compo nd
statements.
f compound statement (written within { }) has a single statement then can be
{} omi
110 JRD Droonammnino Ileing C
Conditional operator
we can use
-or-Ternary Operator as
Sometimes

soen.This operator takes three


nt. This operator
e l estalement. T h
operands, each of which a:shorthand form of if-
ehe Conditional operator is: is
ot
the
c o n d

an
expression. The general
general
S
aN

fitional operator
cexpression1> ?
cexpression2> cexpression3> ;
tor initially evaluates
:

Consion2. Otherwise, it evaluates and returns


retuTnse x p r e s s i o n 2
expression 1. If it is true (non-zero), it evaluates and
ForE x a m p l e
expression3.
(17> 1)?2:3; returns 2
(3 15) ? 10:12: returns 12
classic
classic example oof the
A
her
n o t h e

some value.
r

example
e
ternary operator is to return the bigger of two variables numl
num2 having
and Insteadof

if(numl>Dum2)

big = numl;

else

big=num2;

wecan write big = numl > num2? numl : num2;


here numl > num2 is expresson1, it is evaluate, means expression numl > num2 is checked, if
iste ternary operator returns numl which is then assigned num variable used on left side of=
dherwise if nurml>num2 is false then ternary operator returns num2 which is then assigned to big
Asimple examples of if-else follows next.
Program 6.2. To check whether a number given by user is Positive or Negative. v
MaIn

M num;

drscr( ),
printf( "Pls. Enter A Number: ");
scanf%d", &num);
f num> 0)

printf("You Have Entered A Positive Number.");

else

Pun("You Have Entered A Negative Number:");|Output:


Pls. Enter ANumber: 78
each y, You Have Entered A Positive Number
Contd.
Ontrol Statemostu
Statemo 111
Explanation. Program asks user to enter a number and stores it in variable nuned
checks the condition if(num>0), if value stored in num is greater than 0, condition eval.
and printf statement written in true part of if is executed, otherwise if value given by viulules
than O then condition becomes false and printf statement given in false part of if (d.e. bloc
else) is executed. After this program asks user to press any key and waits
ts for
ock given
for inpu input. w
presses any key from keyboard, program terminates.
Program 6.3. To check whether a number given by user is even or odd.

main()

intnum, rem;
printf Pls. enter a number: ");
scanf(%d", &num); get a numberfrom user */
rem =num %2; * Find remainder, using modulus operator % */
i f num is even, remainder will be 0 when num is divided by 2 *
if(rem0)
printf(Number %d is even.", num);
else
printf(Number %d is odd.", num);
getch):
Output1: Output2:
Pls. enternumber: 25
a Pls. enter number:
a
76|
Number 25 is odd. Number 76 is even.
Explanation. Program asks user to enter a number, when user enters a number, it is stored in
num variable. Then divides
program num by 2 and finds remainder and
stores the remainder in
variable named rem. Then rem is
compared with 0 using comparison operator ==, If num has some
even number stored in it, then rem will be 0
because when any even number is divided
is 0. if the condition is true, by 2, remainder
indicating remainder is 0 and hence the number given by user is even,
printf written in true part of if is executed. But if remainder is not 0, (it can be if
1, the number entered
by user was some odd number) then printf statement given after else i.e
false part of if is executed.
Think!! what output should above program give,
if num given 0 as input.
is
Since there is single statement
inside true part of if and similarly there is single statement inside
false part, that's why curly braces {and} have been
omitted.
6.3.2.2. More examples of if-else
Program 6.4. To find larger of two numbers given by user.

main()

int num1, num2;


clrscr( );
*Ask user to input 2 numbers */
printf(\nPls. Enter two numbers :");
wwww*

Contd.
eanf"od %d", &numl, &num2) :
Scant

which one is larger */


p check
>= num2)
ifnuml
printf First number %d is larger", num1);

else
printf("Second number %d is larger", num2) Output:
Pls. Enter two numbers: 13 56
getch();
Second number 56 is larger

Frolanation. Program asks user to enter two numbers and then checks the condition (using
E
pression) numl >= num2 inside if statement. If this expression is true, then statement
laional expre

inside true part of if prints first number to be larger, otherwise program outputs second
written
number to be larger.

Try Yourself
Program to find smaller of two numbers.
Hint. To write this code, change relational operator >=(greater than or equal to) used the above
rogram inside if statement to <= (less than or equal to) we can find smaller number oftwo numbers.
Program 6.5. To check ifa character given by user is a digit or not.
includecctype.h> header file for library function isdigit() */
main

char ch
clrscr );
printfi("lnPls. Enter any character:");
Scanf(6", &ch); *Note,%cis used to-get value of variable of char data type */
now check, user entered an alphabet or digit */,

ifisdigit(ch))
printf( %c is a digit", ch);
else
printf( oc' is not a digit", ch);
getch();
Outputl: Output2:
Pls. Enter any character: A Pls. Enter any character: 7|
| 'A' is not a digit 7 is a digit

On. PTogram asks user to enter any character, stores the character give by user in
able ch. We
OL
7 T have used library function isdigit() to check if the character given by user is a digit
not. To use1digit( 1

,tis not a ) header file ctype.h must be included. The character given in above example is
s disn
displayed. digit, it is an alphabet. So, if statement returns False and the message 'A' is not a digit

Control State
Program 6.6. To find area of triangle using Hero formula.

NOTE
Hero formula for calculating area of a triangle is Area of Triangle = ySX{S-SI)x(S-S2)

where s1, s2 and s3 are three sides of a triangle. where s is calculated as s=tS2 +S3
2
#include<math.h> /* for sqrt( ) function */
main()

float s1, s2, s3, s, area; * s1, s2, $3 are 3 sides of triangle */
clrscr)
printf("nPls Enter (positive) values of 3 sides of triangle: ");
scanf("%f %f vf ", &sl, &s2, &s3);
S=(s1 +s2+ $3 / 2;
area=sqrt(s * (s- s l ) * (s - s 2 ) * (s s3))

printsf(ns=%5.2f'", s);
printf(nArea of Triangle is: %6.2f ", area);
getch( );
Output:
Pls Enter values of 3 sides
of triangle: 3 68
S = 8.50

Area of Triangle is: 7.64

Explanation. In this program, sl, s2 and s3 three sides of a


value of s using s (s1+s2+s3)/2. Then usings with s1, s2 and s3 we
= triangle. First of all we calculate
formula mentioned above. Library function sqrt (for calculate area of triangle with
and 1or this, header file Math.h has been included inSquare Root) has been used to find square roo,
three sides is smaller than the value of s or if value ofthe program. Note that, if value of any one o
abort, giving run time eror any side is given in-negative,
"Domain Error". program Will
rogram 6.1. To check if
given three sides of a triangle form a
Or
Pythagoras triangle or not.
Ao check if three given
numbers for Pythagoras
ytnagoras
pis perpendicular,triangle is a right angled triplet or not
b is base of triangle in which we have,
main() triangle. b2+p2=h where h is hypotenc neous,

loat sl, s2,


$3;
float s12, s22, 832
clrser()
printf(nPlease Enter values of three
114
scanf"%f9%F%F", &Ls1, &s2,& s3) sides of
triangle: ")%
Contd
s12=s1 s 1
* s2
s2
2 2
3 2 = s 3 * s3;

ifs124s22=s32 I s12+832==s22 I s22+s32-=s12)


rintf"nThese are sides of Pythagorus Triangle "):

rintf"n These are not sides of Pythagorus Triangle "):


else

Output:
P e t c h ) ;

triangle:345
Please Entervalues of three sides of
These are sides of Pythagorus Triangle
of s1, s2 and s3
Explanation. 2, s3
lanation. s1, s2,
are three sides of a triangle, s12, s22, s32 are squares of third side,
checks if squares any
sum of of two sides is equalto square
elIf statement which on is base, which one
is perpendicular and
sides given,
e

se e we don't out of three


c

because
we
will have to check three conditions. If any
one of these
three
is
thisne is hypotenueous,
so we

will be executed else second.


is true, first printf
onditions.

Some extabytesar
what will be the output of foilow
problem using if-else. Can you guess
Here is an interesting
and why ?
ng program
main)
fioatx=l.3;
ifx=13)
printf("Equal !");
else
Output:
printf("Not Equal !! "); NotEqual

63.3. Nested if-else


be organized in
are not restricted
to a single pair They can

that control the execution muluple


Simple if and if-else statements of
linear or branching chains of logic written within another
uenoe of nested to produce we can say that one if or if-else statement can be

Cde. More simply, are called outer


if and inner it.
nested-if. Then they
-EIse statement which is termed
u as ?
from user and check it is 0, Positive or Negative
gram 6.8. To get a number

main)

intnum
printf("Enter a number :");
scanf("%d", &num);
if (num == 0)

printf(You have given a 0");


Contd.
115
if (mm 0)/* thin is nested if

printf" You have given a Negative number"):

else

printf "You have given a Positive number");


Output:
Enter a number: 17
You have given a Positive number
user to enter a number, stores it in
variable num. then it is c
Explanation. Program asks condition is true, program npared
operator = = using if(num =0) If this
wih 0 with comparison
mewsage "You
have given a 0" and ends by
its else part. In case the condition num-
skipping isisfalse
plays
another condition, if (num < 0) is true, program disniar
evutrol entern in else part, here it findsnumber" and ends by skipping else part of if. But if condis
message. "You have given
a Negative
ondition
the message "You have given a Positive number" and ends,
numcd in false program displays

NOTE
Note that. in above program, curly braces may be omitted since each part of if else has a singie
statement in i. But we have not omitted them for the convenience of our readers
wwwwwwwwwwe
Prugram 6,. To check whether a character given by user is a digit or an alphabet.

inchadetype.h> /Header file is included for library functions isdigit() and isalpha() */
man)

charch
cin).
hatf "onPlcase Enter any character :")
Kcanf%
ach) * c is used to read a character from keyboard *
mow cdheck.
user entered an alphabet or a digit */
ifdagtich)).
ruotf c is a
digit "ch);
fusalplai ch))
pnuat ' is au
alphaber",ch);
prounf s
acather a digit nor
Outputl: alphabet" chR
an

Please Bnter any Output2:


Ts an alyhabet character Please Bnter any charcter :*
i s neither a digit nor an alhi
ei e
Td find greatest among three numbers gdven by user.
Program 6.11.

main)

num3;
int numl, um2, to enter 3 numbers
ask user

printf Please enter 3 different numbers "


&num3)
scanfd d d", &numl, &num2,
nested if-else
which one is greatest, using
now find
/outer if */
ifmum num2)
/* inner if - 1
if(numl> num3)
nGreatest is: hd", numl):
printf
else
printf("nGreatest
is: hd"', num3);

else inner if - 2*/


if(num2> num3)
printfnGreatest is: %d", num2); Output:
Please enter 3 different number
else
printf("nGreatest
is: od", num3); 15 23 8
Greatest is 23
getch( ):
*/
}/endof main numbers. Then consider following
cases:

enter 3
asks user to nestedif
Program control enters into
Explanation.
than num2, if yes,
if numl is greater num3 also, yes,
it m e a n s numli
Case 1.First it checks,
numl is greater
than if
if
inside true part of outer if and compares
value of numl. num3, program
a
therefore it will display is not greater than
greatest
than num2 but if numl
Case 2. Even if num1 is greater
display num3 control enters
into is ta
means first if is false so

greater than num2,


nume
Case 3. If numl is not
num3, program
displays
if num2 is greater than
num2 with num3,
part, and compares
num3.
shown in following
figure.
are
Three conditions used with if statements
inner if-1
2nd comparison in

num 3
num 1 num 2

inner if-2
1st comparison in outer if 3rd comparison in
Ilsing C
statement, and as

Program 6.13. To find roots of a quadratic equation.


#includecmath.h> /* header file as a preprocessor directive for sqrt( )*/
main()

float a, b, c. disc, rootl, root2;


clrscr): inbuiltfunction, clears output screen /
printf Please enter values of coefficients a,b,c ");
scanf %f %f%f", &a, &b, &c);
find discriminant */
disc=b* b-4* a* c;
using nested if-else find roots of equation depending on disc */
if disc <0)
printf("nNo real roots.
eise

ifdisc=0) /* nested if else */

printf(nRoots are real and equal ");


rootl= root2 = -b/(2*a);
else

printf("nRoots are real and unequal.");


rootl =
root2
(-b+sqrt(disc) / (2*a);
(-b-sqrt(disc)) / (2*a);
=

printf("nFirst Root %5.2f,=

Second Root %5.2f", rootl, root2);


=

getch)
Output:
Please enter values of coefficients a,b,c :156b
Roots are real-and
First Root unequal.
Explanation. Program asks =-2.00, Second Root = -3.00
it
calculates discriminant to enter 3
user
less than zero. These 3 using disc =
b2- 4ac.numbers,, as coefficients of
of
may not exist. condition
ons are Discriminant
checked one by one nant disc can be
quadratic
quadrauc equatio hen

and equal to , grea


,
greater than of
L 120
depending onn these,
these,
t
mayy ito
roots na, exist or
6.3.4. else-if ladder
else if ladder (also called if-else-if ladder) is another control statement that is
used when
of many conditions have to be checked. So, it is used in the problems having many possible casesene
:

of which one is to be selected and executed, in contrast to if-else statement that is


used for
problems having only two possible cases. It is also known as multi-way decision-making statemem
The syntax or general format or structure of else if ladder :

if(condition_1)

statement_group_l;
else if (condition_2)

statement_group_2
else if (condition_3)

statement group_3;
else if (condition_n)

statement group_n;
Contd.
else

statementgroup_x
end ofelse if ladder
next statement;

rst of all
First of
all conditionl is tested/evaluated, if it is true, group of statements written as
co
ement
ndition_1
group
is false,
i5executed and control jumps to end of else if ladder marked asnextstatement,
tition_1 is false, then control enters in else if part and evaluates next condition written as
ition 2. If condition2 is true, group of statements written as statement_group_ 2 is executed and
er their execution control jumps to end of else if ladder i.e next_statement and so on. f none of t
after
ndition_1, condition_2,.. ., condition_n are true then in else part statement_group_A 1s
nditions condit
eCuted. Note that, there is no condition associated with else part, it is optional to give this else part,
it can occur only at the end of else if ladder.
if
hut given,
Program 6.15. 10 get day number from user and display corresponding day name.
For example ifuser enters 1, output should be Sunday, if user enters 2, output should be Monday
and so on.

main()

intdaynum;
clrscr():
printf(Pls enter Day Number (between 1to7):")
scanf("od", &daynum)
#now display day name using if-else ladder*/
ifdaynum=1) Output1:
printf(n Day is Sunday "); |Pls enter Day Number (between 1 to 7): 3
else ifdaynum== 2) Day is Tuesday.
printf("n Day is Monday ");
else if(daynum==3) Output2:
Pls enter Day Number (between 1to 7): 20
printf("n Day is Tuesday ");
elseif(daynum ==4) Sorry, Wrong Input !
printf("n Day is Wednesday ");
else if(daynum == 5)

printf("n Day is Thursday ");


else if(daynum== 6)
printf("n Day is Friday "):
else if(daynum == 7)

printf"n Day is Saturday ");


else
printf("n Sorry, Wrong Input !")
getch();
uu UIUIycuiTSpOuIV y.
cau
6.5. switch OR switch-case STATEMENT
The
other common control statement (structure) used in C programs is the switch-case statemen
(structure). Instead of accepting any relational expression as in if and if-else statements, switch-case
are
structures
statement is
used to execute alternate blocks of code based on the value of a single variable. This
also referred to as multi-way decision making statement.
switch switch-case
or is very useful decision-making or branch control statement while dealing
with situation when there are two or more alternatives available. However, if-else is used whenthere
are two alternatives available where else-if ladder is used when more than two alternativesavailable.

Sometimes, switch statement is used as an alternative to else -if ladder statement. But there are some
restrictions applied while using switch statement, discussed below in disadvantages section.
Tina C
Decision i s m a d e by switch statement based on its
T a h eb tn o
any floating-point variable. Various argument that can
he
he only of int or char
cases are listed inside body of switch statement
afteranother

h e

orGeneral Format
S y n t a
or
Structure of switch statement is:
switch(expr)
Flow chart of switch statement

case const_:

expr
statementsgroup_I;
break case const_1
case constL2: Statements group_1
case const_2
statements_group_2;
Statements group_2
break;

caseconst_n:
case const_
Statements group_n
statements group _n;
defauit
break; Statements _group_m
default:

statements group_m; remaining part


break:] of programm

data type, it is evaluated. Its resulting value is


Here, expr is any valid expression of int or char
which is also integer or char data nype
coampared with constant given in first case value const_1
as
are executed
stant, if both are then statements written in first group (statements_group_ 1)
equal
ad then execution of break statement causes control to jump
out of switch body and thus skipping
with cons 2, if they
2 of the cases, if they do not match then result of expression expr is compared
executed and break statement
are
then statements falling in second group statements_group_2 the cases from
e s Control to be transferred out of body of switch
statement, so on. If none of
case given at end is
expr then default
esionI to expression_n match with the value expression
of
be default case.
break statement in last case, last case may or may
y ehecuted. I is optional to give

switch statement
3Some important points about Their order does not matter.
Yarious cases given inside switch
can be given in any order.
statements_group_i for which case value, say
Only one group of
statements say,
be executed.
CApressioni matches with expression expr will behavior
Butifit is not given then
case.
2. statement after every
optional to give break called "Fall Through"
which
It will cause a problem
0 switch statement will change. the first case whose
value
then after executing
is missing
m
ans that if break statement
127
Control Statements
matches with expr all case given below (without break) will also execute
prod.
undesirable results. We have incuded a program (to check whether a character give
user is a vowel or consonant)
explain to this. gen by
default label can be given
anywhere inside body of switch but it will execute (and.
surely execute) only if none of the other cases match. If it is not last case of
break is compulsory to use.
switch s
We canwrite switch statement without default label also, i.e default is
optional
Expression must be of int or char data type. Expression expr cannot have float
or drak
data type. e
5 const_1, const_2 etc. must not be relational or logical expressions. Only logical noa
operator is allowed.
6. Maximum 257 cases can be written inside switch.
7. No statements be written outside
can case (and default) labels section.
6.5.2. Advantages of switch statement
1. t is easier to write, read and understand than else if ladder which has
confusing and zi
zag structure.
2. A program written using switch statement is easier to maintain
than an equivalent program
written using else-if ladder. It is also easier to debug.
3. Execute much faster than an
equivalent series of if-else statements, often implememe
by using an indexed branch table For example, deciding
program flow based on a singie
characters value, if correctly
implemented, is vastly more efficient than the alternaüve
reducing instruction path lengths considerably.
4. To deal with
exceptional cases, it offers a default case. Statements written under
are guaranteed to execute if
none of the other cases match.
default
5. There is no strict rule about
ordering the cases, various cases can be written in any ordet
However, when implemented with
fall-through as the default path, switch/case statemenis
are a
frequent source of bugs among even experienced
"break" is almost always the desired programmers, so, in practice. tn
path, but not the default behavior of the switchca
construct (at least in C).
6.5.3. Limitations of switch statement
Switch statement is very useful in
making multi-way decisions and is good substitute of
der, but it has some limitations also. Some of the limitations of else
switch statement are:
1. switch statement can only be used with
expressions of int or char data type (single charactet
only, strings), We cannot use expressions/ values / variables
not

type inside switch statement. If we try, C compiler


of float or double u
gives error: "Switch selection express SIon

must be of integral type".

28
BETWEEN else if LADDER AND
switch STATEMEN
6.6. DIFFERENCES
structure than confusing struc else if ladder
1. switch is more readable and has cleaner
This is due to the compilas
Clure
is faster to execute than else-if ladder. piler
2 switch statement

the switch statement. In the case of the


else-if ladder, the code
code must
ability to optimize However, because each
in the order given in the program. case
process each if statement can easily chano.
on earlier cases, the compiler
within a switch statement does not rely nge
the fastest execution
their order in such a way as to provide
does not allow the use of && and ll operators
3. switch statement
use constant (int or char numeric
4. Various cases written in switch statement can only
such restriction in else if ladder.
values with the 'case statement whereas there is no
be used with int and char data types
5. Expressions written in switch statement can only
whereas, an else-if ladder can any data type
use

6. else if ladder is an effective approach for a smaller number possibilities because, when
number of possibilities increase, the number of comparisons that must be executed

increases as well.
Various cases can be written in any order in switch statement but in else if ladder the
7.
order is fixed by the problem being solved and it cannot be changed.
8.
8. default case can be written anywhere inside switch, not necessarily at the end only, but in
else if ladder, default case written using else (without if) must be at the end only.

9. switch statement uses case and default keywords, else if ladder does not need them.
10 switch statement does not work as desired without break statement, whereas else if
ladder does not require break statement.
11. There is fall through" problem associated with switch statement, but no such problem
is associated with else if ladders
12. Use of curly brace is compulsory in compound statement of else if ladder while no curiy
braces are required in switch.
Program 6.18. To get day number from user and display corresponding day name.
e gee epy ew venenerwwevewvereenevwwem wnweetwMwwwwwwwwwwww.owwwwwwwMMwmVwwww.wwwwwwwwwwwwwwwww.wwwww wwwwwew

main()

int daynum;
printf"Pls enter day number (1-7)");
ooooaaneovdttnenone Contd.
scanf("od", &daynum):
now decide and display day name depending on daynum using switch statement 7
switch(daynum)

case 1:

printf" Sunday ");


break;
case 2:
printf Monday ");
break;
case4: /*Check order does not need to be sorted */
printf( Wednesday ");
break;
case 5:
printf( Thursday "):
break;
case 3 :

printf( Tuesday ");


break;
case 6 :
printf Friday ");
break;
case 7
printf(* Saturday "); Outputl:
break; Pls enter day number (1-7):3
default Tuesday
printf(nWrong Input !");
Output2:
getch); Pls enter day number (1-7)
9
} Wrong Input!
Frogram6.19. To get two number farm user alonaúith
Program 6.21. To display grade of student according to the marks secured using s i
statement.
For example.
Marks Grade
90-100 A+
80- 89 A
70 79 B
60-69 C
50-59 D
40-49 E
0-39 F
c i n e
n tm a s k s

prntl nter marka:");


anf"d" &marka);
rks >=) && marks10) 'range checked
switch marks /10)

case 10:
casc 9:
printf("nGrade is 'A+" "),
break;
case 8:
printf("nGrade is 'A' ");
break;
case

printf("nGrade is B' ")


break;
case 6
printf("nGrade is 'C' ")
break;
case 5:
printf("nGrade is 'D' ");
break;
case 4:
printf "nGrade is 'E' ");
break;
case 3:
case 2:
case 1:
case 0:
printf"nGrade is 'F' ");
break;
Con
else

Output1: Output2
printfnInvalid Marks Input"): Enter marks : 45 Enter marks: -34
Grade is'E' Invalid Marks Inp
Explanation. We have used marks/10 inside switch. An expression is allowed in switchstat
Then we have combined logically, two cases when marks >= 80 and marks =100, inths
marks/10 will return either 9 or 10. So these two cases have been combined. Similarly, ifmark
and marks <40 these cases have also been combined logically.

You might also like