The problem is simple we are given a matrix and is asked to calculate the sum of diagonal (right and left) elements of a matrix in C++.

All we need to do is:

  1. Create a 2D array.
  2. Take input in the array.
  3. Add all elements of left diagonal separately.
  4. Add all elements of right diagonal separately.
  5. Output the result.

The only important point to note is that:

  • For all the element in left Diagonal, their both indexes are same i.e i==j.
  • For all the element in right Diagonal, the sum of their indexes are 1 less than the order i.e i+j == size-1.

Sum of Diagonal Elements of a Matrix in C++

Note: Change the value of size defined as a macro (2nd line) to change the order of matrix.

Output

Sum of Diagonal Elements of a Matrix

If you have any doubts then comment below.

Leave a Reply

Close Menu