"Works" is overrated. The real question is: do you understand why?
Lets take your original code, but remove everything that does not affect the operation of the loops:
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
int x;
for ( x = 100000; x <= 999999; x++ ) {
// x is something
while ( x != 0 ) {
x = x / 10;
}
// x == 0
}
}
|
It should be clear that the
while
loop decreases x to 0.
On start of first iteration of the
for
loop the x == 100000.
At the end of first iteration x == 0.
After iteration the loop increments x (from 0 to 1).
The loop can do new iteration, because 1 <= 999999.
On start of second iteration of the
for
loop the x == 1.
At the end of second iteration x == 0.
After iteration the loop increments x (from 0 to 1).
The loop can do new iteration, because 1 <= 999999.
... forever.
The problem is thus that the while loop affects the for loop.
Should it? No.
The solution, as said, is to make a copy that you can modify without changing the x:
1 2 3 4 5 6 7 8 9
|
int main()
{
for ( int x = 100000; x <= 999999; x++ ) {
int temp {x};
while ( temp ) {
temp /= 10;
}
}
}
|