samedi 12 décembre 2020

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

Aucun commentaire:

Enregistrer un commentaire