Thread: New to C

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    12

    New to C

    Hi. Could someone tell me if this is possible? If so why isnt it running?
    I want to know if you can use if statements in cases.

    Code:
    int main(void);
    {
        int x;
        printf("please enter a number between 1 and 100");
        scanf("%d",&x);
    switch(x)
    {
    case 1:
        if(x <= 50)
        {
            printf("you entered a number below or equal to 50");
        }
        break;
    case 2:
        if (x >50; x<=100)
        {
            printf("you entered a number from 50 to 100 ");
    
    
        }
        break;
    default: 
    
    
            printf("please enter a value between 1 and 100");
            break;
    
    
    }
    
    
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    A switch case like:
    Code:
    switch (x)
    {
    case 1:
        // Do if 1
    break;
    case 2:
        // Do if 2
    break;
    default:
        // Do if anything else
    break;
    }
    is equivalent to:
    Code:
    if (x == 1) {
        // Do if 1
    } else if (x == 2) {
        // Do if 2
    } else {
        // Do if anything else
    }
    so you're checking whether x is smaller or larger than 50 after you establish that x is either 1 or 2 respectively. The first will only be true if x is 1, and the second can never be true. Also, you made a mistake at line #15, when you want to say "this AND that", AND is "&&" in C.
    Last edited by GReaper; 04-11-2017 at 03:59 AM.
    Devoted my life to programming...

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > int main(void);
    Remove the ; from the end of this line.

    > if (x >50; x<=100)
    Decide whether you want boolean and (&&) or boolean or (||).
    ; is not an operator here.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Apr 2017
    Posts
    12
    thank you.

Popular pages Recent additions subscribe to a feed

Tags for this Thread