C++ Program to Find Sum of Diagonal Elements of Matrix

programming

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++:

#include <iostream>
#define SIZE 5
using namespace std;
 
int main()
{
  int matrix[SIZE][SIZE];
  int sum_left =0, sum_right = 0;
  cout << "Enter elements into the matrix \n";

  //Taking input into the Matrix and 
  //Adding if they are diagonal elements
  for(int i=0; i<SIZE ; i++){
    for(int j=0; j<SIZE; j++){
      cin >> matrix[i][j];
      if(i==j)
        sum_left += matrix[i][j];
      if((i+j) == SIZE-1)
        sum_right += matrix[i][j];
    }
  }

  cout << "Sum of Left Diagonal: "<< sum_left << endl;
  cout << "Sum of Right Diagonal: "<< sum_right << endl;

  return 0;
}

Output:

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.

2 thoughts on “C++ Program to Find Sum of Diagonal Elements of Matrix”

  1. for a given array A[10,10], describe an algorithm for calculating the sum of the elements of the main diagonal and the product of the elements of the second diagonal? How to write on delphi 7

Leave a Reply to Saule Cancel reply

Your email address will not be published. Required fields are marked *