For Loops and Arrays

What happens each pass through coupled for loops? I don't quite understand the order of assignment in this nested structure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;

int main ()
{
  for (n=0;n<HEIGHT;n++)
    for (m=0;m<WIDTH;m++)
    {
      jimmy[n][m]=(n+1)*(m+1);
    }
  return 0;
}


Here is how I imagine the program must run:

(n = 0; m = 0) jimmy[0][0] = (0+1) * (0+1)

jimmy[0][0] = 1

(n = 1; m = 1) jimmy[1][1] = (1+1) * (1+1)

jimmy[1][1] = 4

(n = 2; m = 2) jimmy[2][2] = (2+1) * (2+1)

jimmy[2][2] = 9

At this stage it is unclear to me what happens. I presuppose n recycles to 0 and m continues -- breaking the first for loop condition.

(n = 0; m = 4) jimmy[0][4] = (0+1) * (4+1)

jimmy[0][4] = 5
Last edited on
As long as the condition of a loop remains true, the body is executed. That includes any loops it contains.
Ah, so the second loop is repeated three times. I guess this is the sequence of assignment:

[0,0] = 1
[0,1] = 2
[0,2] = 3
[0,3] = 4
[0,4] = 5

[1,0] = 2
[1,1] = 4
[1,2] = 6
[1,3] = 8
[1,4] = 10

[2,0] = 3
[2,1] = 6
[2,2] = 9
[2,3] = 12
[2,4] = 15
Last edited on
Topic archived. No new replies allowed.