0

New to the community and programming. I was curious as to why these two logical statements are equivalent in my program. I can't seem to wrap my head around this specific logic at the moment, and I wanted to understand why it works this way.

Initially, I had written the following:

    char c;
    do {
        cin >> c;
        cout << "You entered: " << c << "\n";
    } while (c != 'Y' || c != 'y' || c != 'N' || c || 'n');
    return 0;
}

However, this does not seem to work unless I use &&. Later, I found out that using or does work, but my negation must be on the outside. These are the two conditionals that confuse me. Why are they logically equivalent?

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n')); // Will run until c is the following
while (c !='Y' && c != 'y' && c != 'N' && c != 'n'); // Will also run but without being negated.

1 Answers1

0

These logical expressions in the do-while loops

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n')); // Will run until c is the following
while (c == 'Y' && c == 'y' && c == 'N' && c == 'n'); // Will also run but without being negated.

are not equivalent.

The expression

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n'));

is equivalent to

while ( c != 'Y' && c != 'y' && c != 'N' && !c && !'n' );

if you have an expression like for example

a == b || c == d

then its negation

!( a == b || c == d )

is equivalent to

!( a == b ) && !( c == d )

and at last to

a != b && c != d

Pay attention to that this do-while loop

char c;
do {
    cin >> c;
    cout << "You entered: " << c << "\n";
} while (c != 'Y' || c != 'y' || c != 'N' || c || 'n');

does not make sense. For example if the user entered 'N' nevertheless the loop continues its iteration because the first subexpression c != 'Y' evalautes to true.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Wow that was incredibly fast. I was re-editing the question posted when I realized I accidentally wrote "==" for the && conditional statement and had to correct it. I do understand they are considered equivalent, but why? – andrerod22 Oct 03 '19 at 16:03