Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Logical Operator in Loop Condition

In the below given code, why the || logical doesn't work, instead the loop terminates specifically when && is used ?

int main() {
    char select {};
    do {
        cout<<"Continue the loop or else quit ? (Y/Q): ";
        cin>>select;
    } while (select != 'q' && select != 'Q'); // <--- why || (or) doesn't work here ??
    return 0;
}
like image 995
Rishi K. Avatar asked Jan 01 '23 10:01

Rishi K.


2 Answers

This loop will go on while select is not q and it's not Q:

while (select != 'q' && select != 'Q'); 

This loop will go on while select is not q or it's not Q.

while (select != 'q' || select != 'Q'); 

Since one of them must be true, it'll go on forever.

Examples:

  1. The user inputs q

select != 'q' evaluates to false
select != 'Q' evaluates to true
false || true evaluates to true

  1. The user inputs Q

select != 'q' evaluates to true
select != 'Q' evaluates to false
true || false evaluates to true

like image 155
Ted Lyngmo Avatar answered Jan 15 '23 11:01

Ted Lyngmo


You want to terminate the loop when select is equal either to 'q' or 'Q'.

The opposite condition can be written like

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( not ( select == 'q' || select == 'Q' ) );

If to open the parentheses then you will get

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( not( select == 'q' ) && not ( select == 'Q' ) );

that in turn is equivalent to

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( select != 'q' && select != 'Q' );
like image 43
Vlad from Moscow Avatar answered Jan 15 '23 12:01

Vlad from Moscow