Cant find what I did wrong!

I'm doing a practice program I found online. http://www.cplusplus.com/forum/articles/12974/
It's titled "While( user == gullible )"
If I enter the number 5 it works, but if the program exceeds 10 trys it keeps going.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 #include <iostream>

using namespace std;
int num;
int trys = 0;

int main()
{
    cout << "Enter a number other than 5: ";
    cin >> num;
    cout << endl;
    while(num != 5 || trys == 10)
        {
            cout << "Enter a number other than 5: ";
            cin >> num;
            cout << endl;

            ++trys;
        }
    if(num == 5)
        {
            cout << "Wow, You are not patient!";
        }

   else if (trys ==10)
   {
       cout << "Congrats, you are more patient than me, You Win!";
   }


    return 0;
}


        
Last edited on
what should it do?

should it exit when trys = 10? If so, your condition inside while is wrong...
it should be: while(num != 5 && trys != 10)
(initialize trys to 1)
im trying to get it to exit the while loop when the number 5 is entered or trys has reached the value 10. So i think it should be || instead of &&? right?
1
2
 while(num != 5 || trys != 10)
 while(num != 5 && trys != 10)
Last edited on
It isn't. Ntrans's is right. I tried it and it ran perfectly. However I am a beginner, so I might explain this poorly or wrong (any experienced programmer please correct me if so). What you were trying to do before doesn't work because the operator "||" (or OR) states that the condition is true if either the right-hand or left-hand argument is true. That means even if you input a 5, the while loop will keep running because 0 != 10 (the loop hasn't run yet so try = 0). So the compiler basically says (in the case of num == 5): "Oh this left-hand argument isn't true, but this right-hand argument is true (since 0 != 10). This means I should keep running the loop." Therefore, if even one of the conditions are true, it keeps running. However, when you replace the || with the && operator, it demands both conditions to be true to keep running. If even one condition is false, then the loop breaks.
EDIT: I made a little mistake with the numbering previous to this edit but the basic idea is the same.
Last edited on
Thanks I understand why it's wrong now!
You're welcome! I'm glad I could help!
Topic archived. No new replies allowed.