how to store a 1 dimensional array in a 2D array?

I have problems with storing a 1D array (size 16) into a 2D array (4 by 4)
what i have come up with is
1
2
3
4
for(int i=0; i<3; i++)//since it is a 4 by 4 matrix so 4 rows...
  for(int j=0; j<3; j++)//
    array[i][j]=list[???]//what should the index be for the 1d array it has 16 cells so how do i fix this?

thanx in advance
The first time, list[0] should be used. The second time, list[1] should be used, etc. You could use a variable "count" that keeps track of wich element should be used:

1
2
3
4
5
6
7
int count=0;
for//...
    for//...
    {
        array[x][y]=list[count];
        count++;
    }
Last edited on
hi thanx-i tried what you told me and it works partially :) but somehow its printing only the first 8 elements of the 1d array---- how can I print the other half? this is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
	int array[3][3];
	int list[16]={2,2,2,3,3,2,4,5,6,7,5,4,3,3,9,0};
	int count=0;
for(int i=0; i<3; i++)//since it is a 4 by 4 matrix so 4 rows...
  for(int j=0; j<3; j++)//
  {
	  array[i][j]=list[count];//
	  count++;
	  cout<<array[i][j]<<" ";
  }


return 0;

}
Last edited on
array[3][3] is a 3 by 3 matrix

array[4][4] is a 4 by 4 matrix, which is what you want. You'll also have to change i<3 and j<3 to i<4 and j<4
but i was taught that the array starts from an index of zero so 0,1,2,3 should give me 4 cells right or am i missing out something?-the loop part, yes i realised i had to change it but the indexes...
Last edited on
If you declare an array, the index hold the number of elements: int array[10], array holds 10 elements. If you access an array, the index is the specific element you're trying to access, where 0 is the first element: array[0] returns the first element and array[9] returns the last element.

EDIT: And you should use i<=3 as condition for both loops; now it only goes through 0,1 and 2.
Last edited on
thanx-it makes sense now :)
If you are translating a 1D array into a 2D array, you only need 1 for loop (to traverse the source array). Untested example:
1
2
3
4
5
6
7
// populate a 2D array from the 1D array
for( int i = 0; i < 16; ++i )
{
    int row = i / 4;
    int column = i % 4;
    var2D[row,column] = var1D[i];
}


If you are translating a 2D array into a 1D array, you would then need 2 for loops (to traverse the source array). Untested example:
1
2
3
4
5
6
7
8
9
// populate a 1D array from the 2D array
for( int j = 0; j < 4; ++j )
{
    for( int i = 0; i < 4; ++i )
    {
        int element = ( j * 4 ) + i;
        var1D[element] = var2D[j,i];
    }
}


I guess that's just my preference to traverse the source array and produce the target array indices.
Last edited on
Topic archived. No new replies allowed.