Leandro
Leandro

Reputation: 183

C++: Outputing Multidimensional Arrays on loop?

Hi everybody I have being trying to do this the whole morning but I can't seem to make it work and is to output a multidimensional array on a loop, let me explain better with a non multidimensional one:

int j;
int line[4] = {1, 2, 3, 4,};


  for(j = 0; j < 4; j ++)
  {

      cout << line[j] << endl;

  }

This works but when for multidimensional arrays comes its headache:

int i, j;
int line[2][2];

line[0][0] = 99;
line[0][1] = 98;
line[1][0] = 97;
line[1][1] = 96;

i = 0;
j = 0;

for(j; j <= 1; j ++)
{
    for(i; i <= j; i ++)
    {
        cout << line[i][j] << endl;
    }
}

Can somebody help me?

Upvotes: 1

Views: 1244

Answers (3)

Dair
Dair

Reputation: 16240

for(int j = 0; j < 2; j++)
{
    for(int i = 0; i < 2; i++)
    {
        std::cout << line[j][i] << endl;
    }
}

What is going on:

So when you enter the loop j = 0. You enter the inner loop i will start at 0 and go to 1 but j will stay that same as 0, then once i = 2 (because 2 is not < 2 it will exit the inner loop and continue on with the 1st loop and j will now equal 1, it will re-enter the inner loop and i will start again at 0 and increment to 1. Then once j = 2 (once again, because 2 is not < 2) it will exit the first loop.

Keeping track you get in this order:

[0][0]
[0][1]
[1][0]
[1][1]

Why this code:

for(j; j <= 1; j ++)
{
    for(i; i <= j; i ++)
    {
        cout << line[i][j] << endl;
    }
}

won't work.

So you enter the 1st loop, j = 0. You enter the second loop, i = 0. It runs through the inner loop once, and you print line[0][0], then i = 1 second time, is 1 <= 0? No. So it exits the inner loop and goes to the first loop. j=1 now. Go into the second loop, you didn't re-initialize i to 0 so i still equals 1. Now you have printed line[1][1], Increment i and you get i = 2. Is 2 <= 1? No. Abort the inner loop. j equals 2 is 2 <= 1 no abort loop. You managed to print:

[0][0]
[1][1]

Upvotes: 0

Pheonix
Pheonix

Reputation: 6052

correction in inner loop condition ! and exchanging of index variables

for(j=0; j <= 1; j ++)
{
    for(i=0; i <= 1; i ++)
    {
        cout << line[j][i] << endl;
    }
}

Edited code ^^

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

To nicely print a 2D array of size n x m, use

for(int i = 0; i < n; ++i)
{
    for(int j = 0; j < m; ++j)
    {
        cout << a[i][j] << " ";
    }
    cout << endl;
}

Upvotes: 1

Related Questions