Multidimensional array logic

Viewed 154

I'm currently being bamboozled by a multidimensional array.

I know a good deal about programming and I was wondering about the logic pertaining to a question from one of quiz modules from cpp institute.

int* t[2] = { new int[2], new int[2] }; 

for (int i = 0; i < 4; i++)     
    t[i % 2][i / 2] = i;
std::cout << t[0][1] + t[1][0] << endl;
delete[] t[0];
delete[] t[1];

When the compiler gets to:

for (int i = 0; i < 4; i++)     
    t[i % 2][i / 2] = i;

I get a little lost, is t[int][int] manipulated every 'i' loop? I know what the answer is so I'm just looking for logic clarification to understand how multidimensional arrays are calculated in loops.

2 Answers

It's a way of iterating through all the combinations that works because it's only a 2x2 array.

It basically has the same effect as

for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++) {
        t[i][j] = i + 2*j
    }
}

But instead of nesting, it's relying on the fact that you can generate the pairs 0, 0, 0, 1, 1, 0, and 1, 1 by performing arithmetic operations on 0, 1, 2, and 3:

i | i % 2 | i / 2
-----------------
0 |     0 |     0
1 |     1 |     0
2 |     0 |     1
3 |     1 |     1

Yes, you can add a print statement if you like to see it for yourself:

for (int i = 0; i < 4; i++) 
{
  std::cout << i % 2 << ", " << i /2 << "\n";
  t[i % 2][i / 2] = i;
}

which prints:

0, 0
1, 0
0, 1
1, 1

That means that it goes through every single cell of your 2D array, in a zig-zag fashion, starting from the top left, finishing at the bottom left.

Related