Program to find sum of diagonal elements of a matrix
Program:
/* cpp program to find sum of diagonal elements of a matrix */
#include"iostream"
using namespace std;
int main()
{
int mat1[10][10], i, j, r1, c1, sum=0;
cout<<"Enter number of rows: ";
cin>>r1;
cout<<"Enter number of columns: ";
cin>>c1;
try
{
if(r1<1 || c1<1)
{
throw 99;
}
}
catch(...)
{
cout<<"Please enter a positive integer.";
}
cout<<"Enter the elements of matrix 1: \n";
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
cin>>mat1[i][j];
}
}
cout<<"Matrix : "<<endl;
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
cout<<mat1[i][j]<<" ";
}
cout<<"\n";
}
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
if(i == j)
{
sum = sum + mat1[i][j];
}
}
}
cout<<"Sum of diagonal elements: "<<sum<<endl;
}
Output:
/* cpp program to find sum of diagonal elements of a matrix */
#include"iostream"
using namespace std;
int main()
{
int mat1[10][10], i, j, r1, c1, sum=0;
cout<<"Enter number of rows: ";
cin>>r1;
cout<<"Enter number of columns: ";
cin>>c1;
try
{
if(r1<1 || c1<1)
{
throw 99;
}
}
catch(...)
{
cout<<"Please enter a positive integer.";
}
cout<<"Enter the elements of matrix 1: \n";
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
cin>>mat1[i][j];
}
}
cout<<"Matrix : "<<endl;
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
cout<<mat1[i][j]<<" ";
}
cout<<"\n";
}
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
if(i == j)
{
sum = sum + mat1[i][j];
}
}
}
cout<<"Sum of diagonal elements: "<<sum<<endl;
}
Output:
Comments
Post a Comment