Home > Enterprise >  Two conditions for DO WHILE loop in C
Two conditions for DO WHILE loop in C

Time:01-19

Could you please explain me why this condition works with || and does not with &&.

I fixed this on my own. I just do not understand why this is OR and not AND.

This program must quit the loop when user inputs Q0.

#include <stdio.h>

int main() {
    
    char character;
    int integer;
    
    printf("Loop started\n\n");
    
    do {
        printf("Enter Q0 to quit the loop: ");
        scanf(" %c%d", &character, &integer);
        
        if (character != 'Q' || integer != 0) {
            printf("Invalid value(s)!\n\n");
        }
        else {
            printf("Correct value(s)!\n");
        }

    } while (character != 'Q' || integer != 0);
   
    printf("\nLoop ended\n");
   
    return 0;
}

Code link

CodePudding user response:

if (character != 'Q' || integer != 0) {
    printf("Invalid value(s)!\n\n");
}
else {
    printf("Correct value(s)!\n");
}

These statements translate to:

"If character is not equal to Q OR if integer is not equal to 0, print invalid value. Else, print correct value."

So, if character is Q or integer is 0, the expression will evaluate to true and correct value would be printed.

Could you please explain me why this condition works with || and does not with &&.

Because if the first operand of the logical AND operator evaluates to false, the second operator is not evaluated. So if character is not equal to Q, then the second expression is never evaluated (even if integer is 0).

If the above code was written as:

if (character != 'Q' && integer != 0) {
     printf("Invalid value(s)!\n\n");
} else {
     printf("Correct value(s)!\n");
}

which translates to: "If character is not equal to Q AND integer is not equal to 0, print incorrect value. Else, print correct value."

It'll only print correct value when the input was Q0 and both the expressions evaluated to true.

  • Related