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(TestCondition-1)
{
            if(TestCondition-2)
             Block-1;
            else     
            Block-2;
}
else
{
            if(TestCondition-3)
             Block-3;
            else     
             Block-4;
}

TestCondition-1, TestCondition-2 and TestCondition-3 are conditions made using relational or logical operators.

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

Block1, Block2, Block3 and Block4 are set of statements, which will be executed depending upon various Conditions. These blocks of statements must contain valid statements of C language.

 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