If-else,Nested if-else. Switch Case Statements
If-else,Nested if-else. Switch Case Statements
Control Statements
i:
makingstatements
Selectionstatements
Iterative statements
ondltional statements Jumping statements
(or)
statements Looping
statements Unconditional statements
Figure-4.1: Control
statements
4.3 DECISION MAKING (OR) CONDITIONALSTATEMENTS
Decision Making Statements: Decision making is about deciding the order of executionof
statements based on certain conditions or repeat a group of statementsuntil certainspecified
conditions are met. The decision making statements help to jump from one section of the program
to another section of the program depending on whether the condition is true or false andthe
main forms are,
• if statement if....else statement
• Nestedif statement Nested if....else statement
else if statement switch statement
91.
statements
Decision making
(or) Conditional statements
if (condition)
statementl;
next statement;
executed.
If the condition is logical true (i.e., non-zero), the statements followingthe if are
skipped and directly
Ifthe condition is logical false (i.e., zero) the statement followed if is
statement is executed.
samplefor Syntax 1
void main( )
void main( )
Out of if
Syntax2: if (condition)
statement 1;
151
Chaptcr.4
statement 2;
next
If condition is true then statement I and 2 are executed and then Next Sta
tement
Simpleif is executed. Ifcondition is false then statement I and 2 are not afi
executed
Bye
statements
Output
HI... next statement
How are you? Figur- 4.3:
Bye.. Flowchart of if
statement
Program-I: write a 'C'
program to print the number entered by
user, only if the
num.
main()
int num;
a numberto
check.\n");
if (num«ø)
// checking
whether number
/* If test is less than ø or not.
conditionis true,
be executed, abovestatement will
Printf(tØThe If otherwise it will
statement in cc' not be executed
programmingis
easy") •
then iOietbct
e. Tbc second if the and
Ptintf displayedon
the
executed true
a to k.
I Nun)bcr•
cit•statcnnentin 'C' programxning
is easy
if....elscStatement
(Two-bay selection)
ay is the basic
a binary expressiom and decision statement for computers,
mas true or false. C then execuung The based on
a set
If programming language dependcngon whether the
statement. An if.. .clse implemcnts
statcmcnt is a paired mo-way sclection With the
statement used to sclccUveIyexecute
Statement: ißelse
statement is an
Ot,sfieda set of statementl will extension of simple if statement.
be executed, If a cond;tjon js
among two alternatives. otherwise statcment2 Will be
So it is called as executec It allows
way dectsion making statement
Ion
Flowchart
If condit
if block condition
statement I ,
statement 3
statement3;
Figure-4.4: Flowchart of If-else statement
If the result of the condition is true, then statement I
is executed, otherwise statement 2 is
executed and then control goes to statement 3 and so on. Both
besimplestaternents or compound statements, I and statement 2 can
From figure 4.4 it is clear that the given condition is evaluated first.
Ifthe condition is true,
Ndte
ment 1 is executed, followed by statement 3. If the condition is false. statement 2
ecuted, is ex.
followed by statement 3.
Note:Jn case of if...else, when if statement is terminated with semicoloncompiler gives
Because, else must be immediately followed by if. Whenever we terminate if'* ith
an
its end of the statement. So, now we doesn't have any relation between if and else.
entered by user is
to
Start
odd.
qstdio.h>
'include
Enter A Number
main()
Yes No
whether remainder is Ø
//checking
or not. Print Even Print Odd
is even. ,
else
is odd." , num); Stop
Figur-4.5
Output-I
Enter a number you want to check.
53
53 is odd.
Output-2
Enter a numberyou want to check.
22
22 is even.
4.3.1.3 Nested if Statements
Nested if Statement: Nested if statement is one in which if statement itself contains
statement. The inner if statement is called nested if statement. The nesting can go to
and it depends on a system capability.
Syntax
if(condition-l)
if (condition-2)
statements;
Control Statements
ondition I
F
condition
statement
if (a > c)
printf("The value a is greater than b and c
statement 1;
else if(condition 2)
huplcr-4
statement
else
Default statements;
Next statement;
In nested else if statement, the number of logical conditions can be checked for executing
various statements. First condition I is checked. Ifconditionl is true then statement-I is executed
and then Next statement is executed. If condition I is false then condition 2 is checked. If Condi.
tion 2 is true then statement-2 is executed and then Next statement is executed. If condition 2 is
false then condition 3 is checked.
This process of checking condition is repeated until any condition evaluates to
true. Ifall
conditions specified with if and else ifevaluates to false then Default Statement
Block associated
With final else is executed.
It must be noted in nested else if statement, if more
than one else if statement is true then
the first else if statement which
satisfies the condition in it will alone execute.
condition I
statement I
condition2
statement 2 statement 3
Figure-4.7: Flowchart of
Program-4: Write a program to else-if
find the largest number
*include <stdio.h> // header in three numbers.
int main() file section
a number:
scanf ("Yod
if(a > 0)
is a positive number
",
56
Control Statements
else if (a < 0)
is a negative
number"
else
printf("\nXd is a zero", a);
return e;
output
Enter a number: 47
.47 is a negative number
Here, the compiler will ask user
to enter the number, when
will check if statement, as if
statementresultedin false theuser enters the number com-
statement,
as the condition is true compiler compilerwill check else if
execute the block followed by else if statement and
thenexit.
4.3.1.5Dangling else Problem
Themajorproblem with nested if statement
is
theambiguityregarding association of else dangling else problem. Dangling else problem is
part with the if part. The general rule is: else part
with the nearest if.
associated is
Syntax:Consider the following nested if-statement
if(conditionl )
if(condition2)
statement I;
else
statement2;
In the above example, statementl is an unambiguously executed when
both the conditions
aretrue,If condition I true and condition 2 is false then statement2 is executed.
If condition I only
fails,then nothing will be executed among statement I and statement 2 and control comes
out of
l' if loop.This problem can overcome by rewriting previous example as either of the
following
exampleI or example 2.
Disadvantages
l. As no. of conditions go on increasing level of indentation also increases.
2. Care should be taken to match corresponding pair of braces.
Example-I
if (conditionl)
{ if (condition2)
statement 1;
Ch apter-4
else
statement2;
condition I
statement 2
condition2
statement I
Figure-4.8: Flowchart
Example-2
if(conditionl)
{ if(condition2)
statementl;
else
statement2;
condition
condition2
statement I statement 2
Figure-4.9: Flowchart
4.3.1.6 nested if-else Statements
In C it is possible to nest if-else statements within one another. In nested if..else statementan
entire if.. .else consfruct can be written within either the body of the if statement or body Ofan
else statement. One or more if statements can be embedded within
the if statement is calledas
nested ifs.
158
Control Statements
if(condition 1)
if(condition 2)
{ if (condition3)
statement 3;
else
statement 2;
else
statement 1;
else
statement 0;
F
condition I
statement 0
condition2
statement 1
condition3
statement 2
statement 3
else
printf("Result:
return e;
Output-I
Enter the two integers to check.
20
15
Result: 20>15
Output-2
Enter two integers to check.
-Be
-3e
Result. • -3e=-3e
4.3.2 Multiway Selection: switch case Statements
This is another form of multiway decision. A multi-way selection statement is used to execute at
most ONE of the choices of a set of statements presented. It is well structured but can only be
used in certain cases where as,
l. Only one variable is tested, all brancheswill depend on the value of that variable. The
variable must be an integral type (int, long, short or char).
2. Each possible value of the variable can control a single branch.
switch Statement: The switch statement allows selection among several alternatives easily. It is also
more readable. It allows checking many alternative conditions and select statements to be executed.
Syntax
switch( value-expression )
{ [case constant-expression 1: statements 1; |
break;
[case constant-expression 2: statements 2;)
break;
(case constant-expression 3: statements 3;)
[default: statements n)
Case keyword is followed by an integer or character constant. Each constant must differ from
Control Statements
the execution of switch statement,
first, expression is evaluated •ahich results in a
The, aloe is c01npared with constant-expressions in
If c(Lsepart. The value is first compared
constant-expressionl. it matches then statementl is executed. ()thcr'Mse value is com-
d next constant-expression and the process continues, If none of the conditions is
then statement associated with the default clause is executed. Default clause is op-
Break statement is closely associated with switch statement. To au)id evaluating any
cases and relinquish control from the switch, terminate each case with break. Break means
Si€itch statement.
Olt from
The execution of switch statement begins with the evaluation of expression. If the values of
matches mth the constant then the statements following this statement execute sequen-
If
till it executes break The break statement tramsferscontrol to the end of the switch statement.
the of expression does not match with any constant, the statement with default is executecL
sote
Valueor variable should be an integer or character type only.
l.
Eachand every case must end with break. If it is not specified, compiler won't give any
error.But the following cases also will be executed.
3. stmts inside [ ] are optional
value=ex resston
Value—constant statement I
Value—constan statement 2
Default statement n
int 1=1;
switch(i)
case 1:
printf ("case 1\n'J);
case 2: 2\n");
Chapter-4
default: printf ("default\n");
Output:
case 1
case 2
default
Explanation for Examplel: Here, i matches first case. So from casel all the SUbsequentcases
and default are also executed. To avoid this we go to break.
Program-6: Write a program that asks user an arithmetic operator('+' , , or and
two operands and perform the corresponding calculation on the operands.
/* 'C' program to demonstrate the working of switch...case statement for addition, SUbtraction
multiplicationand division */
# include <stdio.h>
void main()
char operator;
float num1,num2;
operator +,
operator=getche(); //takes input single operator
two operands:\n");
s canf ( "XfXf", &numl , &num2);
switch(operator)
case '+'
break;
case
print f ( "numl-num2=X.2f", num1-num2);
break;
case
num1tnum2);
break;
case t/' :
Control .Statements
break;
default:
/ * if operator is other than +, * or u/, error
message is shown
printf(Error! operator is not correct");
break;
Output
Enter operator * or /
num1/num2=15
Note:Eventhough there are multiple statements inside a case we need not enclose them in pair
of braces(as in if, else etc.. .).