Copy 1D Array to 2D Array Easily

In this example, i'll show you how to copy a 1-D array into 2-D array in Java. Here is a simple logic that does the task. The task is to create a matrix of certain number of rows and columns which will be filled with the values of a single dimensional array. Here are two cases.

1. If the elements in the 1-D array are more than the grids in the matrix.
2. If the grids are more in the 2-D matrix than the no. of elements in the 1-D array.

class TwoDArray
    public static void main(String args[])
    int a[][]=new int[4][3];
    int d[]={10,20,30,40,50,60,70,80,90,100,110,120};
    int count=0;

        for(int i=0;i<4;i++)
            for(int j=0;j<3;j++)
                if(count==d.length) break;
            System.out.printf("a[%d][%d]= %d\n",i,j,a[i][j]);
    System.out.println("Count is "+count);

Output of the program

a[0][0]= 10
a[0][1]= 20
a[0][2]= 30
a[1][0]= 40
a[1][1]= 50
a[1][2]= 60
a[2][0]= 70
a[2][1]= 80
a[2][2]= 90
a[3][0]= 100
a[3][1]= 110
a[3][2]= 120
Count is 12

Explaining the code

The logic is simple as said earlier. The two dimensional array contains certain number of rows and cols which are usually the factors of the single dimensional array size i.e. 4*3 (row*col) is equal to 12 which is the size of 1-D array.

count=0 is a variable whose initial value will be 0. This variable represents the control which will iterate through the indexes of the 1-D array. So final value of this will be the size of 1-D array.

if(count==d.length) break; Sometimes count can become equal to length of the 1D array, so upon a[i][j]=d[count]; statement execution, we will get an exception i.e. when count becomes d.length and when this statement executes, we get d[d.length] which is absurd, because there will be no index in an array that is equal to it's length. For you to believe what i said, try removing one or more elements from the 1-D array and execute keeping this statement in comments. See what happens. You'll probably get ArrayIndexOutOfBoundsExecption.

a[i][j]=d[count]; Insert the elements into the 2D array. a[0][0] will be first element, a[0][1] will be second one and so on.

count++; Increase the value of count so that next element can be inserted.

Print count, you'll get it equal to the no.of elements in the 1-D array.

Note that, when 2D array size is more than the 1D array the remaining places in the 2D array will not be filled. If 1D array size is more than the 2D array size, then the elements that can be fit into the 2D array will be inserted, remaining however will not be inserted.

Also see subtracting elements in array and adding them up.
Refer to the important binary search integer in array.
Isn't copying 1D array to 2D array easy? Feel free to drop a comment.

Update: Instead of using the variable count you can also use a[i][j]=d[i*3+j]; in this case. Thanks to Jeremy List for the tip.

Posted by at on

Tags: Arrays,