anony
anony

Reputation: 15

While loop wont end with more than one exception

I'm probably missing something very basic but I've searched and haven't found anything similar. The program should end when the variable num1 gets to 10 however it waits for num2 to get to 10 too. I'm pretty sure I'm using the or operator correctly.

#include <iostream>

    using namespace std;

    int main(){
        int num1 = 5;
        int num2 = 0;
        int counter = 0;
        do{
            counter++;
            num1++;
            num2++;
            cout << counter << "  " << num1 << "   " << num2 << endl;
        } while (num1 <= 10 || num2 <= 10);

    }

Upvotes: 1

Views: 68

Answers (4)

Alan Stokes
Alan Stokes

Reputation: 18974

Not is hard; the human brain doesn't deal well with it.

You want to stop the loop when

num1 > 10 || num2 > 10

However, in a while loop you have to say when the loop should continue - which is not (loop should stop).

Now !(a || b) == !a && !b. (That's the law - de Morgan's law.)

So you want

while (!(num1 > 10 || num2 > 10))

Which is

while (!(num1 > 10) && !(num2 > 10))

Which is

while (num1 <= 10 && num2 <= 10)

Upvotes: 2

Jay Miller
Jay Miller

Reputation: 2234

Your while statement says, "continue as long as either num1 or num2 are less than or equal to ten". The statement is a boolean expression "keep going while this is true". If you replace the || (or) with && (and) then you will be saying to continue while both variables are less than or equal to ten.

Upvotes: 4

fhuseynli
fhuseynli

Reputation: 660

F or F = F            F or T = T        T or F = T    T or T = T

So in your case even first comparison is false when num1 is greater than 10, the second comparison makes the whole expression true

Upvotes: 4

Giffyguy
Giffyguy

Reputation: 21302

Use the && operator in place of the || operator.

&& is the Boolean "and" operator, and will provide the functionality you desire.

Upvotes: 3

Related Questions