Nested if statement in C Language

Nested if statement in C Language

In nested if statement, one if statement block is enclosed within another if statement block. The syntax of nested if statement is:
if(Test-1)
{
            if(Test-2)
            Block-1;
            else     
            Block-2;
}
else
{
            if(Test-3)
            Block-3;
            else     
            Block-4;
}

Test-1, Test-2 and Test-3 are conditions

Initially Test-1 condition is evaluated. If it is true, Test-2  condition is evaluated. If Test-2 is also true, Block-1 of statements gets executed. If Test-2 condition is false, Block-2  of statements is executed. If Test-1  condition is false, Test-3 condition is evaluated. If it  is true, Block-3 of statements gets executed. if Test-3 is false, Block-4 of statements gets executed.



 Program to demonstrate the use of nested if statement.

#include<stdio.h>
main()
{
int a;
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");
return(0);
}
Output
Enter a value:=13
Value is between 0 & 5

In the above program, value of variable a has been entered 13. 

Test condition if(a>=0) is true, So condition if(a<=5) is checked. This  condition is false so printf(“\nValue is larger than 5”) gets executed. 


 

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