Why is a loop doing this in C++ -


alright, beginner, take 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, don't understand why program gets x 10 if i'm have if statements check if x < 10 before have 1 added x... please explain.

order of operations is:

  • 1) stop loop if 3) found x >= 10 (if while1 false)
  • 2) print out x
  • 3) check if x >= 10 here , set while1 false if is
  • 4) increment x

when x 9 proceed follows:

  • don't stop loop (while1 true)
  • print out 9
  • x not >= 10 yet, set while1 true
  • x incremented 10
  • don't stop loop (while1 true)
  • print out 10
  • x >= 10, set while1 false
  • x incremented 11
  • we stop loop while1 set false

so, x gets printed out when it's 10. problem that, way check , act on check, 1 loop many before stopping.

one way fix is

while (x < 10) {     cout << x << "\n";     sleep(200);     x = x+1; } 

now loop not execute on same pass through x 10, not pass afterwards.

even better this:

for (int x = 0; x < 10; ++x) {     cout << x << "\n";     sleep(200); } 

which clearer intent on looping on incrementing values of x.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -