Sum of diagonal elements of matrix C++ Program

Simple C++ program to calculate sum of diagonal elements of a matrix.


/* C++ program for Sum of diagonal elements of a matrix */
#include<iostream>
using namespace std;
int main()
{
	int matrix[100][100], m, n ,i ,j, sum=0;
	cout<<"Enter rows of matrix: ";
	cin>>m;
	cout<<"Enter columns of matrix: ";
	cin>>n;
 
	cout<<"Enter matrix elements: "<<endl;
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		{
			cin>>matrix[i][j];
		}
	}
 
	/* add diagonal elements into sum */
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		{
			if(i==j)
			sum=sum+matrix[i][j];
		}
	}
 
	cout<<"Sum of diagonal elements: "<<sum;
 
	return 0;	
}

Program for square matrix

In square matrix, number of rows are equal to number of columns. So if number of rows in a square matrix are n then number of diagonal elements in square are n. We can add diagonal elements using only one for loop.


/* C++ program for Sum of diagonal elements of a matrix */
#include<iostream>
using namespace std;
int main()
{
	int matrix[100][100], m, n ,i ,j, sum=0;
	cout<<"Enter rows of matrix: ";
	cin>>m;
	cout<<"Enter columns of matrix: ";
	cin>>n;
 
	cout<<"Enter matrix elements: "<<endl;
	for(i=0;i<m;i++)
	{
		for(j=0;j<n;j++)
		{
			cin>>matrix[i][j];
		}
	}
 
	/* add diagonal elements into sum */
	for(i=0;i<m;i++)
	{
			sum=sum+matrix[i][i];
	}
 
	cout<<"Sum of diagonal elements: "<<sum;
 
	return 0;	
}



Popular posts from this blog