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:
- Create a 2D array.
- Take inputs in the array.
- Loop from
i=0
toi<(size-1)
- Add all left diagonal elements (i.e. elements satisfying
i==j
) tosum_left
. - Add all right diagonal elements (i.e. elements satisfying
i+j<size-1
) tosum_right
. - End loop.
- 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:
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.
thanks
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