Nested if-else statement

An if statement may have another if statement in the if block. This compound statement is called nested if statement. Any number of if statement can be nested. It has the following forms.

if (expression1)
{
    if (expression2)
    {
. . . 
    /*if block 1*/
    . . . .
     }
     else
     {
    . . .    
    /*else block 1*/
    . . .
      }
}
else
{
    If (expression3)
    {
    . . .
    /*if block 2*/
    . . .
     }
    else
    {
    . . .
    /*else block 2*/
    . . .
     }
  }
  • • If the expression is true, the expression2 will be evaluated, if it is true, the if block1 will be executed, otherwise else block 1 will be executed.
  • • If the expression is false, the expression3 will be evaluated, if it is true, the if block2 will be executed, otherwise else block 2 will be executed.

Figure shows the logic of execution of nested if else statement.


img

A company has introduced a policy of recruiting employees based on their sex and age. The policy is as follows: For a male category the eligibility criteria is the age of a person should have more than 24 and for a female category the age3 should be more than 28. The program segment can be coded as follows:

If (sex is male) 
    {
        If (age > 24)
            printf (“eligible”);
        else
             printf (“Not Eligible”);
        }
    }
    Else
    {
                  If (sex is female)
          {  
        if (age >28)  
               printf (“Eligible”);
        else
                printf (“Not Eligible”);
           }
    }


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext