Learn-dsa..in 30 days!



























CC-1 : Find sum of elements per row of a matrix.

Description:

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

Test cases and expected outputs:

Input Parameters Expected outputs
mat = {
{3,1,5,6},
{9,3,5,0},
{1,1,7,3}};
Sum of rows :
[0] = 15
[1] = 17
[2] = 12
mat = {
{-4,1,5,6},
{9,3,5,-6},
{1,0,-0,3}};
Sum of rows :
[0] = 8
[1] = 11
[2] = 4

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Declare int variable sumRows to hold sum of a particular row.
Declare int array arrSumRows of size equal to number of rows of mat. Elements of arrSumRows will hold the sums of individual rows of mat.
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:
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:
Increment sumRows by mat[rIdx][cIdx] in each iteration.
Once inner loop completes, sumRows has the sum of current row of mat. Store value of sumRows in arrSumRows[rIdx].
After both above loops are completed, arrSumRows contains the sum of individual rows of mat. Return arrSumRows.

Code:

public int[] matRowSum(int[][] mat) throws Exception{
	int sumRow; 
	int[] arrSumRows=new int[mat.length];
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		sumRow=0;
		for (int cIdx=0; cIdx < mat[rIdx].length; cIdx++) {
			sumRow += mat[rIdx][cIdx];
		}
		arrSumRows[rIdx]=sumRow;
	}	
	return arrSumRows;
}

Click here to download and run code and test cases !