rgo rgo - 3 years ago 142
C Question

The conditions is not executing correctly

For age >= 25 and a Unmarried Female the Output is not correct.

A company insures its drivers if either of the following conditions
are satisfied
Driver is married.
Driver is an unmarried, male and above 30 years of age.
Driver is unmarried, female and above 25 years of age.Write a program to decide if a driver is to be insured using logical operators.


#include <stdio.h>


int main()
{
char name[100];
char ms, gender;
int age;

printf("\n\tNAME: ");
scanf("%[^\n]%*c", name);

printf("\n\tAGE: ");
scanf("%d", &age);

printf("\n\tMARRIED [Y/N]: ");
scanf("%s",&ms);

printf("\n\tGENDER [M/F]: ");
scanf("%s",&gender);



if(ms == 'Y'|| ms == 'y')//married
printf("\n\t1. INSURED\n");


else//unmarried
{
if(gender == 'M' || gender == 'm')//male
{
if(age >= 30)
printf("\n\t2. INSURED\n");
else
printf("\n\t3. NOT INSURED\n");
}



else//female
{
if(age >= 25)
printf("\n\t4. INSURED\n");

else
printf("\n\t5. NOT INSURED\n");
}
}

return 0;

}



Kindly help me find the mistake. To locate the mistake I have numbered the output to know. Where the fault is. But I am not able to find any.
the output:

NAME:

AGE: 26

MARRIED [Y/N]: n

GENDER [M/F]: f

5. NOT INSURED

Answer Source

Your variables ms and gender are single characters and not character arrays storing a string.

You are reading into ms with %s format specifier. Use %c format specifier instead which the one for reading into a char.

Like

scanf(" %c",&ms);

instead of

scanf("%s",&ms);

The space before the %c is to ignore the white spaces that may remain in the input buffer which would other have been read into ms instead of the real input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download