mardi 2 novembre 2021

Else statement always runs [duplicate]

I'm making a code so that every time the user inputs a letter that forms the word 'BANANA' in order, the code will input how many words are correct. Whenever the user inputs a wrong letter, the else statement is executed. However, I typed B as the first input. The if condition got executed but the else statement also got executed. I tried typing a wrong input and the else statement got executed twice. How do I fix the code so that the else statement executes (once per input) only when the input is wrong? Here is the code in C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    int a=0;
    int b=0;
    while (a<=6){
    scanf("%c", &c);
        if (c=='B' && a==0){
            a++;
            printf("%d\n", a);
        }
        else if (c=='A' && a==1){
            a++;
            printf("%d\n", a);
        }
        else if (c=='N' && a==2){
            a++;
            printf("%d\n", a);
        }
        else if (c=='A' && a==3){
            a++;
            printf("%d\n", a);
        }
        else if (c=='N' && a==4){
            a++;
            printf("%d\n", a);
        }
        else if (c=='A' && a==5){
            a++;
            printf("%d\n", a);
        }
        else if (c=='/'){
            a--;
            b--;
            printf("%d\n", a);
        }
        else{
            a++;
            b++;
            printf("-1");
        }
        if (a==6 && b==0){
            printf("Potassium!");
            break;
        }
        else if(b>6){
            printf("No potassium.");
            break;
        }
    }
    if (c=='0'){
        printf("No potassium.");
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire