Else if clause in C
Let’s have an example to understand else if clause :
/* else if ladder demo */
main( )
{
int m1, m2, m3, m4, m5, per ;
per = ( m1+ m2 + m3 + m4+ m5 ) / per ;
if ( per >= 60 )
printf ( “First division” ) ;
else if ( per >= 50 )
printf ( “Second division” ) ;
else if ( per >= 40 )
printf ( “Third division” ) ;
else
printf ( “fail” ) ;
}
Program Explanation:
You can note that this program reduces the indentation of the statements. In this case every else is associated with its previous if. The last else goes to work only if all the conditions fail. Even in else if ladder the last else is optional.
Note that the else if clause is nothing different. It is just a way of rearranging the else with the if that follows it. This would be evident if you look at the following code:
Example 2:
Problem Statement:
A company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not.
Solution:
Here after checking a complicated set of instructions the final output of the program would be one of the two—Either the driver should be ensured or the driver should not be ensured. As mentioned above, since these are the only two outcomes this problem can be solved using logical operators. But before we do that let us write a program that does not make use of logical operators.
/* Insurance of driver – without using logical operators */
main( )
{
char sex, ms ;
int age ;
printf ( “Enter age, sex, marital status ” ) ;
scanf ( “%d %c %c”, &age, &sex, &ms ) ;
if ( ms == ‘M’ )
printf ( “Driver is insured” ) ;
else
{
if ( sex == ‘M’ )
{
if ( age > 30 )
printf ( “Driver is insured” ) ;
else
printf ( “Driver is not insured” ) ;
}
else
{
if ( age > 25 )
printf ( “Driver is insured” ) ;
else
printf ( “Driver is not insured” ) ;
}
}
}
Program Explanation:
From the program it is evident that we are required to match several ifs and else and several pairs of braces. In a more real-life situation there would be more conditions to check leading to the program creeping to the right. Let us now see how to avoid these problems by using logical operators.
As mentioned above, in this example we expect the answer to be either ‘Driver is insured’ or ‘Driver is not insured’. If we list down all those cases in which the driver is insured, then they would be:
- Driver is married.
- Driver is an unmarried male above 30 years of age.
- Driver is an unmarried female above 25 years of age.