Overview of Nested if...else Statement

It is perfectly all right if we write an entire if...else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs.

Nested if...else statements has ability to control program flow based on multiple levels of condition.

 

Syntax of Nested if...else Statement:

 

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

 

Rules can be described for applying nested if...else statements.

  1. Nested if...else can be chained with one another.
  2. If the condition is false control passes to else block where condition is again checked with if statement. The process continues if there is no if statement in the last elseblock.
  3. If one of the if statement satisfies the condition, other nested else.. if will not be executed.

 

Flow Diagram

Flow Diagram of nested if else statement
Fig- Flow Diagram of nested if...else statement

 

Example:-

// Program to check whether an integer entered by the user is odd or even

#include <stdio.h>
int main()
{
    int number;
    printf("Enter an integer: ");
    scanf("%d",&number);

    // True if remainder is 0
    if( number%2 == 0 )
        printf("%d is an even integer.",number);
    else
        printf("%d is an odd integer.",number);
    return 0;
}

Output:

Enter an integer: 7
7 is an odd integer.