Nested if else in C

Recommended Topics Before You Continue :

  1. Learn if-else in C
Using only if-else is not sufficient in many cases. We may have to take decision depending upon result of more than one conditions and depending upon the result of first condition we may or may not go for second condition.

Why nesting of if-else is necessary?

While solving day to day problems by means of programming using if-else repeatedly can increase the program code and thus storage. To avoid this we use nesting. Nesting makes it easy for computers to process the code and output the result lot more faster compared to code without nesting.

3. Nested if-else

Example Syntax:
if(condition)
{
	if(condition)
	{
	statement;
	}
	else
	{
	statement;
	}
}
else
{
	if(condition)
	{
	statement;
	}
	else
	{
	statement;
	}
}

For Example:
Consider a program to find maximum of three integers using nested if-else.

#include<stdio.h>

void main()
{
  int a,b,c;

  printf("Enter any three integers:- ");
  scanf("%d%d%d",&a,&b,&c);


 if(a>=b) /* If condition is false if part will be skipped. If true it will check inner if condition if true corresponding part will get executed. If false inner if part will be skipped and else will be executed. */
 {
  if(a>=c)
  {
  printf("%d is maximum",a);
  }
  else
  {
  printf("%d is maximum",c);
  }
 }
 else // Else part will execute only when first if condition is false.
 {
  if(b>=c)
  {
  printf("%d is maximum",b);
  }
  else
  {
  printf("%d is maximum",c);
  }
 }

}

Continue Here : Switch Statement