Nested if statement in C Langauge

Preview

Nested if statement in C Langauge

In nested if statement, one if statement block is enclosed within another if statement block. The syntax of nested if statement is:
if(Condition-1)
{
            if(Condition-2)
            Statement-Block-1;
            else     
            Statement-Block-2;
}
else
{
            if(Condition-3)
            Statement-Block-3;
            else     
            Statement-Block-4;
}
Initially Condition-1 is checked. If it is true, Condition-2 is checked. If Condition-2 is also true, Statement-Block-1 is executed. If Condition-2 is false, Statement-Block-2 is executed. If Condition-1 as false, Condition-3 is checked. If Condition-3 is true, Statement-Block-3 will be executed. if Condition3 is false, Statement-Block-4 will be executed.



 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<=5)
printf(“\nValue is between 0 & 5”);
else
printf(“\nValue is larger than 5”);
}
else
printf(“\nValue is smaller than 0”);
getch();
}
Output
Enter a value:=3
Value is between 0 & 5

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