# Matrix Diagonal Sum in C++

In this tutorial, we will be writing a program to calculate sum of the diagonal elements of a matrix in C++.

### Diagonal Matrix Sum in C++

This question was a part of the Leetcode Biweekly contest #34 on September 5 2020. I will be solving this algorithmic problem in this tutorial.

Our approach is pretty simple. We traverse through the matrix and at each step we take a decision if the element falls in a diagonal.

We see that the constraints say that our matrix may have at most 100 elements. In that case, performing 10000 operations isn’t really time-consuming. Hence our approach will suitably satisfy the test cases appropriately.

Explanation:

Given a 2D array, let’s say

1 2 5

6 9 10

100 9 0

In this case our solution would be to compute the primary and the secondary diagonal in the matrix.

The solution can be calculated as 1+9+0 + 5 + 9 + 100 = 124

The output of the following code will be

124

Take

1 1 1

1 1 1

1 1 1

In this case our answer would be

6

While traversing we need to check if an element is in the principal diagonal. This can be easily checked by seeing if the indices i and j are the same.

On the other hand the elements that fall in the secondary diagonal can be checked by i== size(mat) -i -1.

The code implementation is as follows:

#include<bits/stdc++.h> using namespace std; int myfunc(vector<vector<int>> & mat){ int result=0; for (int i=0 ; i<mat.size(); i++){ for(int j=0; j<mat.size(); j++){ if(i==j or j==mat.size()-i-1) result+=mat[i][j]; } } return result; } int main(){ int n; cin>>n; vector<vector<int>>mine; for(int i=0; i<n; i++){ vector<int>a; for(int j=0; j<n; j++){ int num; cin>>num; a.push_back(num); } mine.push_back(a); } /* for (auto g: mine){ for(auto o: g){ cout<<o<<" "; } cout<<endl; } */ int result= myfunc(mine); cout<<result; return 0; }

## Leave a Reply

You must be logged in to post a comment.