Order of operations is:
- 1) stop the loop if 3) found x was >= 10 (if
while1 is false)
- 2) print out x
- 3) check if x >= 10 here and set
while1 to false if it is
- 4) increment x
When x is 9 we proceed as follows:
- Don't stop the loop (
while1 is true)
- Print out 9
- x is not >= 10 yet, set
while1 to true
- x is incremented to 10
- Don't stop the loop (
while1 is true)
- Print out 10
- x is now >= 10, set
while1 to false
- x is incremented to 11
- We stop the loop as
while1 was set to false
So, 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.