Nested if statement in C Langauge

Preview

Nested if statement in C Langauge

It is basically a multiway decision making statement. In nested if statement, one if statement is enclosed within another if statement.

Depending upon these if statements, particular set of statements will be executed.

The syntax of nested if statement is:
if(Condition1)
{
            if(Condition2)
            Statement-Block1;
            else     
            Statement-Block2;
}
else
{
            if(Condition3)
            Statement-Block3;
            else     
            Statement-Block4;
}
Statement-X;

Condition1,Condition2 and Condition3 are relational or logical expressions which will be checked to see which block of statements should be executed.

Initially Condition1 is checked. If it is true, Condition2 is checked.

If Condition2 is also true, Statement-Block1 is executed. If Condition2 is false, Statement-Block2 is executed.

For Condition1 as false, Condition3 is checked. If Condition3 is true, Statement-Block3 will be executed.

In case Condition3 is false, Statement-Block4 will be executed.

Statement-Block1, Statement-Block2, Statement-Block3 and Statement-Block4 are set of statements, which will be executed depending upon various Conditions.

Statement-X may be a single statement or group of statements which are executed in both the cases of condition to be true as well as false.

Nested if statement can be represented with the help of a flowchart as :

 Program to demonstrate the use of nested if statement.
#include<stdio.h>
#include<conio.h>
main()
{
int a;
clrscr();
printf(“\nEnter a value:=”);
scanf(“%d”,&a);
if(a>=0)
{
if(a<=10)
printf(“\nValue is between 0 & 10”);
else
printf(“\nValue is larger than 10”);
}
else
printf(“\nValue is smaller than 0”);
getch();
}
Output
Enter a value:=6
Value is between 0 & 10

Description of Above Program

In the above program, a has been entered 6. 

Condition if(a>=0) is true, So condition if(a<=10) is checked. This  condition is also true so printf(“\nValue is between 0 & 10”) gets executed. 


Lesson tags: if types in c, nested if in c, nested if statement in c, program of nested if
Back to: C Programming Language