Prettyfly Prettyfly - 21 days ago 6
Java Question

Adding multidimensional arrays of arrays in Java

Bit of a n00b question this one, I guess, but here goes. As part of one of my assignments for my CS degree, we have been given the following problem, but, I just can't figure out where to begin. I guess, having done all the other problems first, my head's a bit fried, as usually I can figure these things out very quickly!

Write a program that initialises two two-dimensional arrays thus

int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};


**The program should add the arrays and put the results into a third two-dimensional array.

e.g if A = {{1,2},{3,4}} and B = {{5,6},{7,8}}, then C = A + B = {{1 + 5, 2 + 6}, {3 + 7, 4 + 8}} = {{6, 8},{10, 12}}

We haven't really touched on multidimensional arrays in great detail, which is where i'm getting stuck. Please don't give me the answer to the problem, that won't help me learn, but if anyone could give a few pointers on the general direction to take with this problem that'd be a great help. So far i've been toying with splitting the initial arrays of 4 arrays into 4 one-dimensional arrays, then performing the calculations with a for loop, but I figured there's bound to be a simpler way, as that would leave me with 12 onedimensional arrays (4 for each of the multidimensional ones, and another 4 onedimensional arrays to make up arrayC, the result of the calculations. 16 is a bit excessive for a simple addition, no?

Please bare in mind I have had VERY little sleep the past few days with various other assignments before you mock my stupidity! Ta :P

######################### EDIT

Thank you all for your help, I got it figured and now understand how to approach these problems, for anyone else with a similar problem, I used the following code;

public class twoDimensionalArray {

public static void main(String args[]){

int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};
int arrayC[][] = new int[4][4];

for(int i = 0; i < arrayA.length; i++) {
for(int j = 0; j< arrayA[0].length; j++) {
arrayC[i][j] = arrayA[i][j] + arrayB[i][j];

} // end j for loop
} // end i for loop

for (int i = 0; i < arrayC.length; i++) {
for (int x = 0; x < arrayC[i].length; x++) {
System.out.print(arrayC[i][x] + " | ");
}
System.out.println();
}
} // end main
} // end class

Answer

Declare and initialize new 2-dimensional array "arrayC" to hold your results. Use nested for loops to loop through both arrays and add the results, storing the results in your new 2D array.

Comments