0

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

  • 5
    Does this answer your question? [When to use If-else if-else over switch statements and vice versa](https://stackoverflow.com/questions/427760/when-to-use-if-else-if-else-over-switch-statements-and-vice-versa) – alex01011 Dec 12 '20 at 16:36

1 Answers1

0

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()

anotherOne
  • 1,513
  • 11
  • 20