I need to calculate the sum of two diagonals in a matrix in C++, I already have a solution for that but I must be dumb because I cant understand what it is doing, so I would like to know if there is another version which I can understand. here is the code which does the job:
cout<<"Jepi rangun e matrices"<<endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat
cin>>n;
cout<<"Tani jepi elementet e matrices"<<endl; // lexohet matrica
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cin>>a[i][j];
}
d=0;
s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i==j)
d=d+a[i][j];
if(j==n-i+1 || i==n-j+1)
s=s+a[i][j];
}
The part that is difficult to understand is
if(j==n-i+1 || i==n-j+1)
s=s+a[i][j];
Here is the entire code that I changed but it doesnt work for the secondary diagonal:
#include <iostream>
using namespace std;
int main()
{
int d=0,s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme
int i,j,n;
int a[5][5];
cout<<"Jepi rangun e matrices"<<endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat
cin>>n;
cout<<"Tani jepi elementet e matrices"<<endl; // lexohet matrica
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cin>>a[i][j];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
d+=a[i][j]; //principal diagonal
if(i+j==n-1)
s+=a[i][j];//secondary diagonal
}
}
cout << d << endl;
cout << s << endl;
cin.get();
cin.get();
return 0;
}
See Question&Answers more detail:os