While loop question.

In the following while loop....why does the and "&&" work but not the or "||"?

Isn't saying and for each condition saying that the variable "s" has to satisfy all of the conditions? Wouldn't || more appropriate since it is saying it has to meet this, or this, or this, or that?


Here is the exercise.

Given a string variable s that has already been declared , write some code that repeatedly reads a value from standard input into s until at last a "Y" or "y"or "N" or "n" has been entered.






1
2
3
4
  while ((s!="Y" && s!="y" && s!="N" && s!="n"))
{
    cin >> s;
}
If you use
while((s!="Y" || s!="y" || s!="N" || s!="n"))
no matter what input you enter this expression will always evaluate to true coz you cant enter any value so that all the tests wold be false

if you enter Y
(false || true || true || true) == true

if you enter y
(true || false || true || true) == true

if you enter N
(true || true || false || true) == true

if you enter n
(true || true || true || false ) == true

if you enter anything else
(true || true || true || true) == true

if you want to use || you have to write
while (!(s=="Y" || s=="y" || s=="N" || s=="n"))
Last edited on
I feel so stupid because I've tackled problem way harder than this but...what makes the and "&&" different?
(a && b ) gives the result TRUE when both sides, the a AND the b, are true.

(a || b ) gives the result TRUE when either side, the a OR the b, is true.

Thanks. Now I get it. Man this board is so helpful.
Topic archived. No new replies allowed.