Write a method to find the sum of each row in a 2-dimensional integer array. The return value is an array of integers.
public static int[] sumOfRows(int[][] arr) {
int[] sumArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int sum = 0;
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
sumArray[i] = sum;
}
return sumArray;
}
In the main method, get and display the sum of rows for both array1 and array2.
public static void main(String[] args) {
int[][] array1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] array2 = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
int[] sumOfRowsArray1 = sumOfRows(array1);
int[] sumOfRowsArray2 = sumOfRows(array2);
System.out.println("Sum of rows for array1: " + Arrays.toString(sumOfRowsArray1));
System.out.println("Sum of rows for array2: " + Arrays.toString(sumOfRowsArray2));
}
Write a method to find the sum of each column in a 2-dimensional array. The return value is an array of integers.
public static int[] sumOfColumns(int[][] arr) {
int[] sumArray = new int[arr[0].length];
for (int i = 0; i < arr[0].length; i++) {
int sum = 0;
for (int j = 0; j < arr.length; j++) {
sum += arr[j][i];
}
sumArray[i] = sum;
}
return sumArray;
}
In the main method, get and display the sum of columns for both array1 and array2.
public static void main(String[] args) {
int[][] array1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] array2 = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
int[] sumOfColumnsArray1 = sumOfColumns(array1);
int[] sumOfColumnsArray2 = sumOfColumns(array2);
System.out.println("Sum of columns for array1: " + Arrays.toString(sumOfColumnsArray1));
System.out.println("Sum of columns for array2: " + Arrays.toString(sumOfColumnsArray2));
}