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.
#include <iostream>
usingnamespace 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!";
}
elseif (trys ==10)
{
cout << "Congrats, you are more patient than me, You Win!";
}
return 0;
}
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)
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.