C++ Program to Find Sum of Matrix Diagonal

Write a C++ Program to Find the Sum of Matrix Diagonal with an example. In this C++ example, we used for loop to iterate matrix rows and adding items of the diagonal items (sum = sum + sumDgnalArr[rows][rows]).

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns, sum = 0;
	
	cout << "\nPlease Enter the Matrix rows and Columns =  ";
	cin >> i >> j;
	
	int sumDgnalArr[i][j];
	
	cout << "\nPlease Enter the Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> sumDgnalArr[rows][columns];
		}		
	}

 	for(rows = 0; rows < i; rows++)
  	{
  		sum = sum + sumDgnalArr[rows][rows];
  	}
  	
  	cout << "\nThe Sum of Diagonal Elements of a Matrix = " << sum;

 	return 0;
}
Please Enter the Matrix rows and Columns =  3 3

Please Enter the Matrix Items
10 20 30
40 50 60
70 80 90

The Sum of Diagonal Elements of a Matrix = 150

In this C++ program to calculate the sum of the Matrix Diagonal, we used extra cout statements to show you the iteration number, row, column value, and the sum at each iteration.

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns, sum = 0;
	
	cout << "\nPlease Enter Matrix rows and Columns to find Diagonal Sum =  ";
	cin >> i >> j;
	
	int sumDgnalArr[i][j];
	
	cout << "\nPlease Enter the Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> sumDgnalArr[rows][columns];
		}		
	}

 	for(rows = 0; rows < i; rows++)
  	{
  		cout << "\nIteration = " << rows + 1 << ", Row Number = " << rows << " and Sum = " << sum;
  		sum = sum + sumDgnalArr[rows][rows]; 		
		cout <<  "\nsumDgnalArr["<<rows<<"]["<< rows <<"] = " << sumDgnalArr[rows][rows] << 
			" and sum + sumDgnalArr["<<rows<<"]["<<rows <<"] = " << sum << endl;
  	}
  	
  	cout << "\nThe Sum of Diagonal Elements in this Matrix = " << sum;

 	return 0;
}
C++ Program to Find Sum of Matrix Diagonal 2

C++ Program to Find Sum of Matrix Diagonal using a While Loop

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns, sum = 0;
	
	cout << "\nPlease Enter Matrix rows and Columns to find Diagonal Sum =  ";
	cin >> i >> j;
	
	int sumDgnalArr[i][j];
	
	cout << "\nPlease Enter the Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> sumDgnalArr[rows][columns];
		}		
	}

 	rows = 0; 
	while(rows < i)
  	{
  		sum = sum + sumDgnalArr[rows][rows];
  		rows++;
  	}
  	
  	cout << "\nThe Sum of Diagonal Elements in this Matrix = " << sum;

 	return 0;
}
Please Enter Matrix rows and Columns to find Diagonal Sum =  3 3

Please Enter the Matrix Items
10 22 33
44 55 66
77 88 99

The Sum of Diagonal Elements in this Matrix = 164