WHILE with || or && I'm confused by the output

Hey folks.

I'm reading a C++ Beginner Book and try to comprehend some code examples. So far so good.

int cnt = 1;
int cnt2 = 1;
while ((cnt < 3) || (cnt2 < 3)) {
  cnt++;
  cnt2 = cnt2 + 50;
  Serial.print(cnt2);
}

The output is 51 and 101. I dont get it. I use a OR - why is there a second loop? because the cnt2 variable is after the first loop greater than 3?

When I'm changing the || Operator to && (AND) than the outcome is as i expected with or...

Maybe you can help me here. Thanks!

Then you seem to have the meaning of || and && swapped in your head :wink:

2 Likes

Tell us what you think || (OR) should do ? :thinking:

2 Likes

since it is OR, only one of the two has to be true for the while loop to continue, and cnt < 3 is true twice but not after the third increment.

if it is AND, they both have to be true.

2 Likes

Maybe research "de Morgan"

1 Like

I have always used || and && in IF condition.... I wasn't aware that the condition applies to the CONTINUE... that's why the && makes more sense now....

Thanks for your answers :slight_smile:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.