'C - While Loop Condition has OR with Char: Not Terminating
When using the logical OR operator in a while loop for Char values, the program does not run correctly.
The code is the following:
#include <stdio.h>
void main() {
char choice = 'y';
while( choice != 'n' || choice != 'N') {
int num;
printf("\nEnter any number: ");
scanf("%d", &num);
int i = num - 1;
while(i >= 1) {
num *= i;
i--;
}
printf("Factorial is: %d\n", num);
printf("Do you want to continue? \n");
printf("Enter n to quit or y to continue\n");
scanf(" %c", &choice);
}
}
Ouput:
Enter any number: 3
Factorial is: 6
Do you want to continue?
Enter n to quit or y to continue
n
Enter any number: 3
Factorial is: 6
Do you want to continue?
Enter n to quit or y to continue
N
Enter any number:
If I change the while statement, for example, to:
while( choice != 'n' ) {
The program runs fine. It is the logical OR that is creating an error.
Why is this issue occurring? And how do I make the program run with the OR logical operator?
Solution 1:[1]
The logical OR operator || evaluates to true if either expression is true.
So if choice is N then choice != 'n' is true, and if choice is n then choice != 'N' is true. If choice is neither of those, then both are true. So the full condition will always be true.
You want to instead use the logical AND operator &&. This evaluates to true only if both expressions are true.
while( choice != 'n' && choice != 'N') {
Solution 2:[2]
If you put n, choice != 'N' is true and it continues.
If you put N, choice != 'n' is true and it continues.
There should be && instead of ||.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbush |
| Solution 2 | the_bond_007 |
