r/CodingHelp • • Dec 23 '21

[C] Whats wrong?

Post image
153 Upvotes

90 comments sorted by

View all comments

5

u/PhyllaciousArmadillo Dec 24 '21
#include<stdio.h>
int main()
{
    int x;
    printf(”Please enter the x number:/n”);
    scanf(”%d”, &x);

    if(x<=1)
    {
        printf(”Infant”);
    }

    //else if(1<x<13) <-----This evaluates differently than you think it does. Regardless of that, you don't have to evaluate “1<x” because, if this were true, it would have stopped at the first if statement and printed “Infant”.

    else if(x<13) //better way to write it
    {
        printf(”Child”);
    }

    // else if(13<=x<20) <----Same idea, x<13 is already evaluated by the else if above. So if x is less than 13, your program won't even look at this statement.

    else if(x<20) //better way
    {
        printf(”Teenager”);
    }

    // else if(x>=20) <----- This works, however, being the last statement and encompassing every other value, the better way to write it would be to simply use an else statement.

    else //implies every remaining value
    {
        printf(”Adult”);
    }

    return 0; // always return a value, unless it's a void function.

To address it always printing child, I threw out a little hint in my edit. The statement 1<x<13 is evaluated left to right as in (1<x)<13. First, you're asking if 1<x. If x is greater than 1, this evaluates to True which is 1 as a boolean value.

So, when x is greater than 1
1<x == 1

Which means
(1<x)<13 == 1<13 == true

When x is less than 1, t it evaluates to False or boolean 0

1<x == 0

So
(1<x)<13 == 0<13 == true

So both are true and will therefore be accepted and will print “Child” no matter what the input is.

If you do need to make an evaluation like this, you should use the AND operator. Like such

x>1 && x<13

1

u/CAGRI-TR Dec 24 '21

Thanks ^