Learn-dsa..in 30 days!



























CC-2 : Find sum of elements per column of a matrix.

Description:

Given an input matrix mat. Find and return sum of elements of each column of the matrix.

Test cases and expected outputs:

Input Parameters Expected outputs
mat = {
{7,1,4,1},
{9,9,3,0},
{2,1,4,3}};
Sum of columns : 18,11,11,4
mat= {
{3,1,-5,6},
{-9,3,2,7},
{-1,0,0,9}}
Sum of columns : -7,4,-3,22

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize int variable sumCols to 0.
Initialize int array arrSumCols with size mat[0].length to hold the sum of the elements of columns.
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
Within above loop, iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Increment arrSumCols by mat[rIdx][cIdx] in each iteration.
When above for loops are completed arrSumCols will have sum of each column of the matrix.
Reference code is given below. For sake of brevity, code for validation for the method’s input parameters is not provided. To ensure that the code works properly, ensure input parameters are valid before calling the method.

Code:

public int[] matArrayColumnSum(int[][] mat) throws Exception{
	int sumCol; 
	int[] arrSumCols=new int[mat[0].length];
	for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
		sumCol=0;
		for (int rIdx=0; rIdx < mat.length; rIdx++) {
			sumCol += mat[rIdx][cIdx];
		}
		arrSumCols[cIdx]=sumCol;
	}	
	return arrSumCols;
}

Click here to download and run code and test cases !