This C++ program finds the sum of the diagonal elements of a matrix. The row and column values of the matrix are read into the variables m and n. Then the elements are read one by one into the 2D array a[][] using a nested for loop, at the same time the address of the first element in each row is stored to the pointer array p[]. Then the program uses for loop to find the sum of the first and second diagonal elements and the result is displayed to the output screen.
Program
//matrix diagonal elements sum c++
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],*p[10];
int m,n,i,j,s1=0,s2=0,t;
cout<<"Enter the order of matrics: ";
cin>>m>>n;
cout<<"Enter the elements\n\n";
for(i=0;i<m;i++)
{
p[i]=&a[i][0];
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"\n\nFirst diagonal elements are\n\n";
for(i=0;i<n;i++)
{
cout<<*(p[i]+i)<<"\t";
s1=s1+*(p[i]+i);
}
cout<<"\n\nSecond diagonal elements are\n\n";
t=n;
for(i=0;i<n;i++)
{
cout<<*(p[t-1]+i)<<"\t";
s2=s2+*(p[t-1]+i);
t--;
}
cout<<"\n\nSum of first diagonal elements is: ";
cout<<s1;
cout<<"\n\nSum of second diagonal elements is: ";
cout<<s2;
getch();
}
3 comments:
Very very smart logic :O
Still don't believe this is possible!
Thanks Tony.
Good logic
Post a Comment