# Copy an array from 1D to 2D

4 posts / 0 new
heartin
Copy an array from 1D to 2D

Write a program to copy a 1-dimension array with 12 elements into a 2-dimensional array with 3x4 elements. Print the 2-D array as a matrix.

Note

If someone has already given an answer for above problem, try other combinations like a 1-dimension array with 8 elements into a 2-dimensional array with 2x4 elements.

Hint

1. You can directly initialize a 1-D array and then use a for loop to copy. 1-D array has only one index as arr1[i] and 2-D array has two indexes as arr2[j][k].
2. To print the 2-D array as a matrix, use two for loops. Outside loop is for rows and inner one for col. Inner one will be executed for all rows.

ALL THE BEST!!!

sneha
Copying elements from ID to 2D array

This program has been rewritten again below with heading 'Modified Program after Review'. Retaining the original program for reference.

package com.javajee.Utils;

public class CopyArray {

int[] arr1={1,2,3,4,5,6,7,8,9,10,11,12};
int rowSize=3;
int columnSize=4;
int[][] arr2=new int[rowSize][columnSize];

public static void main(String[] args) {
CopyArray CA=new CopyArray();
CA.copyElems(CA.arr1);
CA.printElem(CA.arr2);

}

public void copyElems(int[] A){
int k=0;
for(int i=0;i<rowSize;i++){
for(int j=0;j<columnSize;j++){
arr2[i][j]=A[k];
k++;
}
}

}

public void printElem(int[][] B){
for(int i=0;i<rowSize;i++){
for(int j=0;j<columnSize;j++){
System.out.print(B[i][j]+" ");
}
System.out.println();
}
}

}

Was it useful?
heartin
Good, but can be better...

Here arr1 is an instance variable. So should we really have to pass it into copyElems function? If so, why not sending arr2?

It would be great if you can try to make these methods indpendent of static / instance variables so that it can be reused in other places.

NOTE:

1. If rewriting, please write a new one with a heading like 'Modified Program after Review'.
2. In the original program, add a note on top that the program has been rewritten.
Was it useful?
sneha
Modified Program after Review

package com.javajee.Utils;

public class CopyArray {

public static void main(String[] args) {
int[] arr1={1,2,3,4,5,6,7,8,9,10,11,12};
int[][] arr2=new int[3][4];
copyElems(arr1,arr2);
printElem(arr2);

}

public static void copyElems(int[] A,int[][] B){
int k=0;
for(int i=0;i<B.length;i++){
for(int j=0;j<B[0].length;j++){
B[i][j]=A[k];
k++;
}
}

}

public static void printElem(int[][] B){
for(int i=0;i<B.length;i++){
for(int j=0;j<B[0].length;j++){
System.out.print(B[i][j]+" ");
}
System.out.println();
}
}

}

Was it useful?