Sunday, 18 August 2013

Nested for loops seem to execute separately for some reason

Nested for loops seem to execute separately for some reason

I am attempting to process a two-dimensional array in C. I tried two
nested for loops, but it seems that the two loops execute separately. I
expect that the inside loop loops eight times for each loop of the outside
loop, resulting in eight times the number of outside loops being the total
number of loops.
As a simplified test, I tried this:
#include <stdio.h>
int main() {
int x = 0;
int y = 0;
for (; x < 7; x++, printf("(%d,%d)", x, y)) {
for (; y < 8; y++, printf("(%d,%d)", x, y)) { }
}
}
This resulted in these results:
(0,1)(0,2)(0,3)(0,4)(0,5)(0,6)(0,7)(0,8)(1,8)(2,8)(3,8)(4,8)(5,8)(6,8)
Could somebody please explain to me why this might be happening? Thanks.

No comments:

Post a Comment