I have to do the following exercise:
Make a function that receives a two-dimensional array and displays the sum of each row and each column on the console. The number of rows does not have to be equal to the number of columns.
My biggest problem is with irregular arrays, that is, for example this:
int array[][] = { {2, 4, 6},
{3, 1, 7, 7} };
I have to make a function that returns in a new array the sum, as the statement says, of columns and rows.
I have only done a very small part of the code, the idea, so to speak, because it drives me crazy to create an array whose final size I don't know.
public static int[][] sumArray(int[][] array) {
int[][] result = null;
// Suma de columnas.
for (int i = 0; i < array.length; i++) { // Primera dimensión
for (int j = 0; j < array.length; j++) { // Segunda dimensión
result[i][j] += array[i][j];
}
}
}
Thank you!
The first thing you need is to know the number of rows and columns that you are going to add. The rows part is easy, you just have to check the size of the received array:
For the columns we will have to keep the maximum size of all of them, going through each row and see which is the longest:
And now you just have to go through all the cells and add the values where it corresponds, with the loop you already have:
Now you will only have to show the result by console: