Control Statements
Control Statements
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.
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
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
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
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
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
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*/
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)
else
called false
part of if*/
group of statements (or control statement)
*/
this block or group is executed when condition is false
Evaluate False
Condition/expression
True
an
expression. The general
general
S
aN
fitional operator
cexpression1> ?
cexpression2> cexpression3> ;
tor initially evaluates
:
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;
M num;
drscr( ),
printf( "Pls. Enter A Number: ");
scanf%d", &num);
f num> 0)
else
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()
Contd.
eanf"od %d", &numl, &num2) :
Scant
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
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
because
we
will have to check three conditions. If any
one of these
three
is
thisne is hypotenueous,
so we
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
main)
intnum
printf("Enter a number :");
scanf("%d", &num);
if (num == 0)
else
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
main)
num3;
int numl, um2, to enter 3 numbers
ask user
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
num 3
num 1 num 2
inner if-2
1st comparison in outer if 3rd comparison in
Ilsing C
statement, and as
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
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)
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:
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
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
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:
case 10:
casc 9:
printf("nGrade is 'A+" "),
break;
case 8:
printf("nGrade is 'A' ");
break;
case
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.