Nested if else statement in c


  • In this kind of statements number of logical conditions are checked for executing various statenents.
  • Here, if any logical condition is true the compiler executes the block followed by if condition otherwise it skips and executes else block.
  • In if.. else statement else block is executed by default after failure of condition.
  • Nested if...else statements has ability to control program flow based on multiple levels of condition.

    Syntax:

    if(condition)
    {
       // Statements inside body of if
    }
    else if(condition)
    {
       //Statements inside body of else if
    }
    else
    {
       //Statements inside body of else
    }

Flow Diagram

    Flow Diagram of if else statement

Example:

#include 
int main()
{
   int var1, var2;
   printf("Input the value of var1:");
   scanf("%d", &var1);
   printf("Input the value of var2:");
   scanf("%d",&var2);
   if (var1 != var2)
   {
	printf("var1 is not equal to var2\n");
	//Nested if else
	if (var1 > var2)
	{
		printf("var1 is greater than var2\n");
	}
	else
	{
		printf("var2 is greater than var1\n");
	}
   }
   else
   {
	printf("var1 is equal to var2\n");
   }
   return 0;
}

Output:

Input the value of var1:12
Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1