Main Diagonal Sum

You are given a square matrix of size N x N. Your task is to calculate the sum of the elements present on the main diagonal of the matrix.

The main diagonal consists of elements whose row index and column index are equal, starting from the top-left corner and ending at the bottom-right corner.

Example 1:

Input:

Matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Output:

15

Explanation:

The main diagonal elements are 1, 5, 9. Their sum is 1 + 5 + 9 = 15.

Example 2:

Input:

Matrix = [
    [-10, 20],
    [30, 40]
]

Output:

30

Explanation:

The main diagonal elements are -10, 40. Their sum is -10 + 40 = 30.

Now Your Turn!

Pick the correct output for the given input

Input:

Matrix = [
    [10, 2, 4],
    [-3, -4, 6],
    [8, -6, 1]
]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= N <= 100
  • -105 <= Matrix[i][j] <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int mainDiagonalSum(int** arr, int N) {
// Write your logic here
 
return 0;
}
};
Test Case

Input:

Matrix