Nested if Statement in C Programming Language

Rumman Ansari   Software Engineer   2019-03-31   10756 Share
☰ Table of Contents

Table of Content:


A nested if is an if statement which contains another if or else. Nested ifs are very common in programming.

In discussions of the general format of the if statement, we indicated that if the result of evaluating the expression inside the parentheses is true, the statement that immediately follows is executed. It is perfectly valid for this program statement to be another if statement, as in the following statement:

Syntax

The syntax for a nested if...else is as follows ?

if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
   if(Boolean_expression 2) {
      // Executes when the Boolean expression 2 is true
   }
}

Practical Approach of Nested if

#include
    void main(){
	int x =15;
	int y = 20;

	 if( x == 15 ) {
	   if( y == 20 ) {
	      printf("X = 15 and Y = 20\n");
	     }
      }
  }
  }
}
 
X = 15 and Y = 20
Press any key to continue . . .

When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else. Here is an example:

#include
    void main(){
	int a=2, b=3, c=8,d=0;
	int i=15, j=20 , k=300;
	if(i == 15) {
	    if(j< 25) a = b;
	       if(k > 102) c = d; // this if is
	       else a = c; // associated with this else
	 }
    else a = d; // this else refers to if(i == 10)

    printf("%d \n",c);
  }
 
0
Press any key to continue . . .

As the comments indicate, the final else is not associated with if( j < 25) because it is not in the same block (even though it is the nearest if without an else). Rather, the final else is associated with if(i==15). The inner else refers to if(k>102) because it is the closest if within the same block.

Another Example

 
#include
int main()
{ 
int a = 3;
      int b = 1;

      if( a == 3 )
	  {
         if( b == 1 ) // this is nested if
         {
           printf("a = 3 and b = 1 \n");
         }
      }
      else
      {
	   printf("a != 3 and b != 1 \n");
	  }
}
 
a = 3 and b = 1
Press any key to continue . . .

Another Important Example

 
#include
int main()
{ 
int a = 4;
      int b = 1;

      if( a == 3 )
	  {
         if( b == 1 ) // this is nested if
         {
          printf("a = 3 and b = 1 \n");
         }
      }
      else
      {
		if( b == 1 ) // this is nested if
		  {
		   printf("a != 3 and b = 1 \n");
          }
	  }

}
 
a != 3 and b = 1
Press any key to continue . . .