I wonder why while (selection != 'q' && selection != 'Q') works but while (selection != 'q' || selection != 'Q') does not work. It will never terminate the loop. When I use else if (selection == 'q' || selection == 'Q' ) (with ||) it's working fine. Can someone help?
#include <iostream>
using namespace std;
int main()
{
char selection{};
do{
cout << "\n--------------------------"<< endl;
cout << "1.Do this" << endl;
cout << "2.Do that" << endl;
cout << "3.Do something else" << endl;
cout << "4.Quit" << endl;
cout << "\nEnter your selection" << endl;
cin >> selection;
if (selection == '1')
cout << "You chose 1 - doing this" << endl;
else if (selection == '2')
cout << "You chose 2 - doing that" << endl;
else if (selection == '3')
cout << "You chose 3 - doing something else" << endl;
else if (selection == 'q' || selection == 'Q' )
cout << "Goodbye" << endl;
else
cout << "Unknown option -- try again" << endl;
}
while (selection != 'q' && selection != 'Q');
}
Let's look at your proposed condition, which you are wondering why it doesn't work:
while (selection != 'q' || selection != 'Q')
In order for this while loop to terminate the loop, the above expression must evaluate to false. That's how a while loop works. In other words:
!(selection != 'q' || selection != 'Q')
must be true. Basic rules of boolean logic show that this expression is logically equivalent to
selection == 'q' && selection == 'Q'
which, obviously can never happen. The selection value can never be q and Q at the same time. Only Schrödinger's cat can do that.
To add onto the answer. you could also use !(selection == 'q' || selection == 'Q') where in this case, when q, !(true||false)=false and when Q, !(false||true)=false and everything else, !(false||false)=true.
#include <iostream>
using namespace std;
int main()
{
char selection{};
do{
cout << "\n--------------------------"<< endl;
cout << "1.Do this" << endl;
cout << "2.Do that" << endl;
cout << "3.Do something else" << endl;
cout << "4.Quit" << endl;
cout << "\nEnter your selection" << endl;
cin >> selection;
if(selection == '1')
cout << "You chose 1 - doing this" << endl;
else if(selection == '2')
cout << "You chose 2 - doing that" << endl;
else if (selection == '3')
cout << "You chose 3 - doing something else" << endl;
else if (selection == 'q' || selection == 'Q' ){
cout << "Goodbye" << endl;
break; //break in case of 'Q'||'q'
}
else
cout << "Unknown option -- try again" << endl;
}while(true);
Just to add on to the explanation already answered. This works as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With