user705185
user705185

Reputation:

Do While Loop Question

do 
{
  cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
  ch=getch();
} while ( ch !='q' || ch != 'Q');

Why will the code on top not work while the code below does? I tried it with parenthesis around each statement in numerous ways and the compiler would pop an error every time until I regrouped them as I did below. I'm just wondering why it does this.

do 
{
  cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
  ch=getch();
} while ( !(ch=='q' || ch=='Q') );

I'm using Visual Studio 2008 as my compiler; x86 architecture.

Upvotes: 3

Views: 562

Answers (7)

MikeTeeVee
MikeTeeVee

Reputation: 19392

When inverting all your logic using '!', you did right by reversing the conditional operators "==" to "!=", but you forgot to reverse the logical operators "||" to "&&". Thus, this should be correct:

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

I use C#, so while code above will work, I would have used this instead as it is easier to read:

while (ch.ToUpper() != 'Q');

Upvotes: 0

SoapBox
SoapBox

Reputation: 20609

You've got the logic backwards, that's my negating it works. By DeMirgan's laws, !(ch == 'Q' || ch == 'q') is the same as ch != 'Q' && ch != 'q'.

Since a if it cannot be both little q and big Q at the same time, while (ch != 'Q' || ch != 'q') doesn't make sense because if it is 'Q' then it won't be 'q', and vice versa.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754715

The problem is your boolean logic is off and the two while conditions are not the same.

  • Top: Character is not 'q' or is not 'Q'
  • Bottom: Character is not ('q' or 'Q')

The Top will return true for every single character possible. The bottom will return true for every character except 'q' and 'Q'

Upvotes: 2

Adam Byrtek
Adam Byrtek

Reputation: 12202

!(ch=='q' || ch=='Q') is equivalent to ch!='q' && ch!='Q'. See also De Morgan's laws.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

(ch != 'q' || ch != 'Q') is always true: "ch is not equal to 'q' or ch is not equal to 'Q'".

Upvotes: 3

jwueller
jwueller

Reputation: 30996

I think you want this in your first example:

ch !='q' && ch != 'Q'

You want that the input is not q AND not Q.

Upvotes: 0

YXD
YXD

Reputation: 32511

Learn De Morgan's laws

(not A) or (not B)

is not the same as

not (A or B).

Upvotes: 16

Related Questions