Summary: In this programming example, we will learn to write a C++ program to find the sum of diagonals elements of a matrix (2D array).

A square matrix has two diagonals i.e. left and right diagonal.

The left diagonal elements have equal row and column indexes i.e. i==j and the sum of indexes of the right diagonal elements is one less than the size of the matrix i.e. i+j == size-1.

Using these relations we can easily get the diagonals elements and find their sum.

Steps to find the sum of diagonal elements of a matrix:

  1. Create a 2D array.
  2. Take inputs in the array.
  3. Loop from i=0 to i<(size-1)
  4. Add all left diagonal elements (i.e. elements satisfying i==j) to sum_left.
  5. Add all right diagonal elements (i.e. elements satisfying i+j<size-1) to sum_right.
  6. End loop.
  7. Output the sum values.

Here is the implementation of the steps in C++:


Sum of Diagonal Elements of a Matrix

In this program, we have explicitly defined the size of the matrix i.e. 2D array using Marco #define SIZE 5.

Inside the nested for loop, after the user inputs the array element we check whether it is a diagonal element. If yes, then we add it to the respective sum variable.

In this tutorial, we learned to find the sum of diagonals elements in C++ programming language.

Leave a Reply

12 − 5 =