Nesting of if …else
When there are another if else statement in if-block or else-block, then it is called
nesting of if-else statement.
Syntax is
if (condition)
{
If (condition)
Statement1;
else
statement2;
}
Statement3;
Example:
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The value is:1
If….else LADDER
In this type of nesting there is an if else statement in every else part except the last
part. If condition is false control pass to block where condition is again checked
with its if statement.
Syntax is
if (condition)
Statement1;
else if (condition)
statement2;
else if (condition)
statement3;
else
statement4;
This process continue until there is no if statement in the last block. if one of the
condition is satisfy the condition other nested “else if” would not executed.
But it has disadvantage over if else statement that, in if else statement whenever
the condition is true, other condition are not checked. While in this case, all
condition are checked.
Example:
// C program to illustrate nested-if statement
#include <stdio.h>
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
printf("i is 10");
// Since i is not 10
// Check if i is 15
else if (i == 15)
printf("i is 15");
// Since i is not 15
// Check if i is 20
else if (i == 20)
printf("i is 20");
// If none of the above conditions is true
// Then execute the else statement
else
printf("i is not present");
return 0;
}
Output:
i is 20