1

I wrote the following program in C and when the input is 'U', 'F' and '27', the output is 'The driver is not insured.' Can anyone please explain why? Shouldn't the output be, 'The driver is insured?'

The Program:

#include <stdio.h>

int main() {
    int age;
    char sex, ms;
    printf("Enter the marital status(M for married and U for unmarried), sex (M for male and F for female) and age of driver:\n");
    scanf("%c %c %d", &ms, &sex, &age);
    if (ms == "M")
        printf("The driver is insured\n");
    else if (age > 30)
        printf("The driver is insured\n");
    else if (sex == "F") {
        if (age > 25)
            printf("The driver is insured\n");
    } else
        printf("The driver is not insured\n");
    return 0;
}

I am aware that I can use else if (sex == F && age > 25) instead of nesting the last if command but I want to know what happens when I write it this way and why does the out put show 'The driver is not insured.'

chqrlie
  • 131,814
  • 10
  • 121
  • 189

3 Answers3

2
#include <stdio.h>
int main()
{
    int age;
    char sex, ms;
    printf("Enter the marital status(M for married and U for unmarried), sex (M for male and F for female) and age of driver:\n");
    scanf("%c %c %d", &ms, &sex, &age);
    if (ms=='M')
        printf("The driver is insured\n");
    else if (age>30)
        printf("The driver is insured\n");
    else if (sex=='F')
    {
        if (age>25)
        printf("The driver is insured\n");
    }
    else
        printf("The driver is not insured\n");
    return 0;
}

More

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
0

I think it is because your loop is leaking.

I think you should create in this way:

loop1: Check Unmarried/ Married

loop2: Check Male/Female

Loop3: Check Age

Note: loop3 inside loop2 inside loop1

I hope it helps.

Developer
  • 21
  • 6
-2

Antonin Gavrel explained it well, you are comparing a character type variable wih string. as double qout(") is used for strings. Use as follow if (ms=='M') else if (sex=='F')

Haris Shafiq
  • 513
  • 3
  • 5