When I typed while (c != 'Y' || c != 'n' || c !='y' || c != 'N'); , my program just loops over, and over, and over again, even if I don't fulfil the condition, AKA, if I enter values Y, y, N or n. However, if I were to replace the || with &&, the program works as intended. Is it due to a logic flaw of mine? The way I see it, if the character entered doesn't equate to Y, or y, or N, or n, the program will repeat itself. But now, from what I understand, it's supposed to be, if the character entered doesn't equate to Y, and y, and N, and n, the program will repeat itself. Would appreciate it if someone could correct me. Below's my code.
1 Answer
You want the loop to continue if c
is none of the four characters. But you're writing
c is not Y OR c is not y OR c is not N OR c is not n
and at least three of those four conditions are true, so the whole thing is true. If for example c
were 'Y'
, all three other conditions would be true. If it were 'R'
, all four would be true, and only this is the case where you want to repeat the input, which means you need AND (&&
) and not OR (||
).
The opposite of
c == 'Y' || c == 'n' || c =='y' || c == 'N'
is
c != 'Y' && c != 'n' && c !='y' && c != 'N'
Blame De Morgan's Laws ;-)
-
I think I get what you're getting at. To further clarify, does that mean that if any condition out of the 4 conditions were true, no matter 1 or 3 of them, it'd mean that the whole condition is true, and hence the loop would run? So does this also mean I should not understand OR in computing as how I'd understand it in the physical world?– JonNov 29, 2017 at 3:55
-
-
Usage in daily language doesn't always follow the same logic. Computer's OR is not a XOR (eXclusive OR), and even exclusive or on multiple things is not an any-of-n-choices, as the operators work with two values only.– BlauelfNov 29, 2017 at 7:20