简体   繁体   中英

When exactly do we use “if else-if” and “case break” statements in C language? I wrote 2 codes for a problem, but the difference I don't understand

I hope the problem question is understood based on my code,

Here is the code I've written using case-break statements:

#include<stdio.h>
int main()
{
    int x;
    printf("Pick an integer from 1, 2 and 3: ");
    scanf("%d", &x);

    switch(x)
    {
        case 1:
            printf("1 is a unique number.\n", x);
            break;
        case 2:
            printf("2 is the smallest and the only even prime number.\n", x);
            break;
        case 3:
            printf("3 is the first odd prime number.\n", x);
            break;
        default:
            printf("I haven't even asked you to enter %d\n", x);
    }
    return 0;
}

This is the code I have written using if else-if statements:

#include<stdio.h>

int main()
{
    int input;

    printf("Enter any one of 1, 2, and 3 ");
    scanf("%d", &input);

    if(input==1)
        printf("%d is a unique number", input);
    else if(input==2)
        printf("%d is the only even prime number", input);
    else if(input==3)
        printf("%d is the smallest odd prime number", input);
    else
        printf("I did not even ask you to enter %d", input);

    return 0;
}

Thank You

If you are checking for different values of the same variable, then it's up to you whether to use switch() or else if()

If you are checking for the value of 2 or more variables (and possibly even their combinations) then you'd better use else if()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM