+ 1
Required output not displayed in sololearn c++ compiler.
#include <iostream> using namespace std; //program to sum elements lying on any of the diagonal of matrix int main() { int i,j,m,sum,ar[10][10]; cout<<"Enter number of columns\n"; cin>>m; if(m>10) { cout<<"max(m)=10"; m=10; } for(i=0;i<m;i++) { for(j=0;j<m;j++) { ar[i][j]=1; } } for(i=0;i<m;i++) { sum+=(ar[i][i]+ar[i][m-1-i]); } if(m%2==1) sum-=ar[m/2][m/2]; cout<<sum; return 0; }
3 Answers
+ 2
while declaring the variable "sum" initialize it as 0.
It will give you the desired output .
Hope it solves your problem.
+ 1
To sum the elements of other diagonal.
let ar[3][3] be there.
first diagonal is ar[0][0],ar[1][1],ar[2][2]
second diagonal is ar[0][2],ar[1][1],ar[2][0]
0
Why do you sum diagonal like this: sum+=(ar[i][i]+ar[i][m-1-i]); ? sum+=ar[i][i]; is sufficient.