Reputation: 25
Alright, beginner, take it easy. Thanks.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x = 0;
bool while1 = true;
while (while1)
{
cout << x << "\n";
sleep(200);
if (x < 10)
{
while1 = true;
}
else if (x >= 10)
{
while1 = false;
}
x = x+1;
}
cin.get();
}
Alright, so I don't understand why the program even gets x to 10 if I'm have the if statements check if x < 10 before I have 1 added to x... please explain.
Upvotes: 0
Views: 184
Reputation: 121
What you are doing is:
...
Your program start another loop since while1 = true
Best thing to do is to just
int x = 0;
while(x < 10)
{
cout << x << endl; //this way your program will only print 0 to 9
sleep(200);
x++; //this is the same as x = x+1
}
If you insist on using your own code, I guess you can replace your while1 = false with break;
else if (x >= 10)
{
break;
}
break; will let you break out of the while loop if x >= 10 without increasing x or going through the loop again...
Should be safe unless you are going to do more things in that while loop...
Upvotes: 0
Reputation: 21773
Order of operations is:
while1
is false)while1
to false if it isWhen x is 9 we proceed as follows:
while1
is true)while1
to truewhile1
is true)while1
to falsewhile1
was set to falseSo, x gets printed out when it's 10. The problem is that, the way you check and act on the check, you do one loop too many before stopping.
One way to fix this is
while (x < 10)
{
cout << x << "\n";
Sleep(200);
x = x+1;
}
Now the loop will not execute on the same pass through that x is 10, not the pass immediately afterwards.
Even better is this:
for (int x = 0; x < 10; ++x)
{
cout << x << "\n";
Sleep(200);
}
Which is clearer about its intent over looping over incrementing values of x.
Upvotes: 4
Reputation: 1
if x>=10 in the loop than obviously the loop will iterate one more time when it reaches to 10 in the while loop
Upvotes: 0
Reputation: 1922
If you don't want x to be printed after x >= 10, do the checking after you increment x.
#include <iostream>
#include <windows.h>
using namespace std;
int main(
{
int x = 0;
bool while1 = true;
while (while1)
{
cout << x << "\n"
x++;
Sleep(200);
if (x < 10)
{
while1 = true;
}
else if (x >= 10)
{
while1 = false;
}
}
cin.get();
}
Upvotes: 0
Reputation: 2028
else if (x >= 10)
{
while1 = false;
}
x = x+1;
I understand the question as: Why is x getting to 10? Is this correct?
Your while loop does not immediately exit when setting while1 to false. So of course x will equal to 10 after exiting the loop as x is increase after checking that, so x will in fact be 11 after this code segment.
Upvotes: 0
Reputation: 12670
The program gets x
to 10
because the x = x + 1
happens outside of the if
.
So during one execution of the loop, it will check, then if x is less than 10 it will make while1
true. Otherwise it makes while1
false. After that it increases x
no matter what.
Then it repeats this process if while
is true.
Upvotes: 0