[1/2] Driver insurance using if-else statement
This program is one of the two methods that can be used for solving the given example.
Note that this problem has certain drawbacks compared to the other one. This program mainly has the problem of indentation and the program starts creeping to the right as the no. of conditions increases. The best way to tackle this problem is to solve the problem by using Logical Operators.
A company insures its drivers in the following cases:
- If the driver is married.
- If the driver is unmarried, male and above 30 years of age.
- If the driver is unmarried, female and above 25 years of age.
In all the 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 insured or not.
#include<stdio.h>
main()
{
char sex,ms;
int age;
printf ("Enter age, sex, marital status:");
scanf ("%d %c %c", &age, &sex, &ms);
if (ms=='M')
printf ("The 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");
}
}
}
Note that this problem has certain drawbacks compared to the other one. This program mainly has the problem of indentation and the program starts creeping to the right as the no. of conditions increases. The best way to tackle this problem is to solve the problem by using Logical Operators.
A company insures its drivers in the following cases:
- If the driver is married.
- If the driver is unmarried, male and above 30 years of age.
- If the driver is unmarried, female and above 25 years of age.
In all the 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 insured or not.
#include<stdio.h>
main()
{
char sex,ms;
int age;
printf ("Enter age, sex, marital status:");
scanf ("%d %c %c", &age, &sex, &ms);
if (ms=='M')
printf ("The 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");
}
}
}
Comments
main()
{
char sex,ms;
int age;
printf ("Enter age, sex, marital status:");
scanf ("%d %c %c", &age, &sex, &ms);
if (ms=='M')
{
printf ("The driver is insured");
}
else if (sex=='M' && age>30)
{
printf ("Driver is insured");
}
else if (sex=='F' && age>25 )
{
printf ("Driver is insured");
}
else
{
printf ("Driver is not insured");
}
}
whats the diff then ?