[Solved] How do for loops work in C? [closed]


First of all, x and n never change, so let’s put their values in the for loops and remove them from the code, to make it easier to understand.

 int k = 0;
 for (int i = 0; i < 7; i++) {

   for (int j = 0; j < 5; j++) { 
      b[i][j] = a[k];
      k++;
   }

   i++; 

   for (int m = j; m >= 0; m--) {
      b[i][m] = a[k];
      k++;
   }
}

• Before first iteration of the i loop

 i = 0;
 k = 0;

j loop goes from 0 .. 4

b[0][0] = a[0];  // b[i][j] = a[k]
b[0][1] = a[1];
b[0][2] = a[2];
b[0][3] = a[3];
b[0][4] = a[4];

j loop exits because j has reached 5.

k is same as j (starts at 0, incremented like j)

i is incremented to become 1

m loop goes from 5 .. 0

b[1][5] = a[5]; // b[i][m] = a[k]
b[1][4] = a[6];
b[1][3] = a[7];
b[1][2] = a[8];
b[1][1] = a[9];
b[1][0] = a[10];

m loop exits with

m = -1;
k = 11;

• At 2nd iteration of i loop:

i = 2;  (because i *for* loop increments it)
k = 11;

j loop goes from 0 .. 4

b[2][0] = a[11];  // b[i][j] = a[k]
b[2][1] = a[12];
b[2][2] = a[13];
b[2][3] = a[14];
b[2][4] = a[15];

j loop exits because j has reached 5.

k = 16;

i is incremented to become 3

m loop goes from 5 .. 0

b[3][5] = a[16]; // b[i][m] = a[k]
b[3][4] = a[17];
b[3][3] = a[18];
b[3][2] = a[19];
b[3][1] = a[20];
b[3][0] = a[21];

.
.
.

3

solved How do for loops work in C? [closed]