c
C Programming Tutorial : Introduction

C Conditional Statements - Nesting of if- else

When an if else statement is present inside of the if block or the else block. This is called nestling of if else statements. Here is an example of nesting where we have if… else inside both if block and else block.

Syntax

if(condition)
    {
        //Nested if else inside the body of "if"
      if(condition2) 
        {
        //Statements inside the body of nested "if"
   	     }
     else 
        {
        //Statements inside the body of nested "else"
         }
    }
else 
    {
    //Statements inside the body of "else"
    }
 
nested-If-Statement Flow chart

While nesting if-else statements, sometimes confusion may arise in associating else part with appropriate if part: Let us take an example

Example-1

if (grade== 'A')
    {
    if(marks>95)
        printf("Excellent") ;
    }
else
    printf("Work hard for getting A grade");
 

If we write the above code without braces as

Example-2

if(grade=='A')
    if(marks>95)
        printf("Excellent") ;
else
        printf("Work hard for getting A grade"); 

Here the else part is matched with the second if, but we wanted to match it with the first if. The compiler does not associate if and else parts according to the indentations, it matches the else part with closest unmatched if part. So whenever there is doubt regarding matching of if and else parts we can use braces to enclose each if and else blocks.

Example-1

/* Program to find largest number from three given numbers*/
#include<stdio.h>
#include <conio.h>
    void main( )
    {
        int a, b, c, large;
        printf("Enter three numbers ") ;
        scanf("%d%d%d",&a,&b,&c) ;
    if (a>b)
        {
        if(a>c)
            large=a;
        else
            large=c;
        }
    else
        {
        if (b>c)
            large=b;
        else
            large=c;
    	}
printf ("Largest number is %d\n", large) ;
getch();
}
 

Example-2

/*P5.5 Program to find whether a year is leap or not*/
#include<stdio.h>
#include<conio.h>
    void main()
    {
        int year;
        printf ("Enter year :“);
        scanf ("%d ", &year) ;
        if (year%100==0)
            {
                if (year%400==0)
                    printf ("Leap year\n");
                else
                printf ("Not leap\n");
            }
        else
            {
                if (year%4==O)
                    printf ("Leap year\n");
                else
                    printf("Not leap\n");
            }
    getch();
    }