Learn-dsa..in 30 days!



























CC-5 : Find sum of diagonal elements.

Description:

Given matrix mat, find the sum of the diagonal elements of the matrix.

Test cases and expected outputs:

Input1 Expected outputs
mat = {
{7,1,4},
{9,0,3},
{2,1,-1}}
Sum Of Diagonals: 6
mat= {
{3,1,-5,6},
{-9,3,2,7},
{-1,0,0,9},
{4,2,6,9}}
Sum Of Diagonals: 15

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize a variable sumDiagonal for storing the value of sum of diagonal elements.
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:
If (rIdx==cIdx):
Set sumDiagonal+=mat[rIdx][cIdx].
Once above loops are completed, return sumDiagonal.

Code:

public int matArraySumDiagonal(int[][] mat) throws Exception{
	int sumDiagonal=0;
	for (int idx=0; idx < mat.length; idx++) {
		sumDiagonal+=mat[idx][idx];
		}
	return sumDiagonal;
}

Click here to download and run code and test cases !