jeudi 5 septembre 2019

why when I add "else" after an "if" statement the code doesn't function correctly?

I'm writing code that takes any number from the user, it tells the user if the input contains 3,6, or 9. else, the code should print out the same input. I managed to get the "if" correctly, if the user input any number, the code will tell if it contained 3, 6, or 9. However, when I add the "else" part, the code doesn't work anymore, and it wont tell if the inserted number contained 3, 6, or 9.

This code can detect any number:

int i;

    printf("Enter a number:");
    scanf_s("%d", &i);
    int L = i;
    int n = 0;

    while (i > 0)
    {
        n = i % 10;
        i = i / 10;
        if (n == 3 || n == 6 || n == 9)
        {
            printf("There is a 3 or 6 or 9.");
            break;
        }

adding these lines to the above code wont make it work correctly

else
        {
            printf("%d", L);
            break;
        }


input: 300

output without else statement:"There is a 3 or 6 or 9." (Correct)

output with else statement: 300 (incorrect)

why is that?

Aucun commentaire:

Enregistrer un commentaire