Given a matrix, print the sum of the column elements in the matrix.
For example, consider the matrix below.
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
The column sum of the matrix above is as follows.
12
15
18
12
) indicates the sum of the elements of the first column, i.e., 1
, 4
, and 7
.15
) indicates the sum of the elements of the second column, i.e., 2
, 5
, and 8
.18
) indicates the sum of the elements of the third column, i.e., 3
, 6
, and 9
.Create an array of size equal to the number of columns. This array is used to store the column sum of every column. Let the array be colSum
.
Iterate through every column of the matrix and execute the following:
colSum
array defined in Step 1 of the algorithm.Return the colSum
array.
import java.util.Arrays; public class Main{ private static int[] printColSum(int[][] matrix){ int numRows = matrix.length; int numCols = matrix[0].length; int[] colSum = new int[numCols]; // Loop through the given number of columns for(int i = 0; i < numCols; i++) { // define the sum variable to get the column sum int sum = 0; // Loop through the elements in the column for(int j = 0; j < numRows; j++) // add every element to the sum variable sum += matrix[j][i]; // add the column sum to the result array colSum[i] = sum; } return colSum; } private static void printMatrix(int[][] matrix){ for (int[] row : matrix) System.out.println(Arrays.toString(row)); } public static void main(String[] args){ int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8 , 9}}; printMatrix(matrix); System.out.println("The column sum of the above matrix is as follows:"); int[] colSum = printColSum(matrix); for(int i: colSum) System.out.println(i); } }
RELATED TAGS
CONTRIBUTOR
View all Courses