The if-else-if statement

When the else part of an if statement contains another if-else statement, an extremely useful construction is got which is mostly used for multiway decision. This construction is called if-else chain and. This takes the form

if (condition_1)
   Statement 1;
else
   if (condition_2) 
      Statement2;
else
   Statement3;

Each condition is evaluated in order and if any condition is true, the corresponding statement is executed and the remainder of the chain is terminated. The final else statement is only executed if none of the previous conditions is satisfied.

Example 2.4

Consider the example of identifying the status of an individual, based on the person's age. The tasks include

  • Reading the age
  • If the individual is aged between l and 18 years, it should be decided that he is a minor.
  • If the age is below 40 years, the person is a major
  • If the age exceeds 40 years, the person is an adult.
  • Adjudging the status of the individual after the decision and finally.
  • Printing the status of the individual.
#include <stdio.h>
int main()
{
    int age;
    printf ( "Enter the age value
" ); 
    scanf ("%d", &age);
    if (age >= 1 && age <=18)
        printf ( "The individual is a minor");
    else
       if (age >= 19 && age <=40) 
          printf ("The individual is a major");
       else 
           if (age >=41 && age<=120)
              printf ("The individual is an adult);
           else
              printf ( "Invalid age value is entered");
}
​