An alternate solution for this bad loop
Posted on 2007-12-04
I finally got this loop to change but I can't fiqure out another way to stop
while (x = 1)
cout << "x is: " << x << '\n';
The above code executes a never ending loop displaying x is: 1 out to the console.
This happens because condition x = 1 is reset to 1 (never changes) every time the loop is performed, even if the x++ increment is added.
One way to stop this loop is as follows&.
int x = 1; // initialize interger x to equal 1
while (x < 2) // execute loop while x is less than 2
cout << "x is: " << x << '\n'; // console out x is: 1
x++; // increment x by 1 (this will change the loop condition and terminate the loop
I need an alternate way to stop this loop. Can you help me?