+ 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; }

7th Nov 2016, 9:47 AM
Megatron
Megatron - avatar
3 Réponses
+ 2
while declaring the variable "sum" initialize it as 0. It will give you the desired output . Hope it solves your problem.
29th Nov 2016, 11:04 AM
Rishabh Agrawal
Rishabh Agrawal - avatar
+ 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]
8th Nov 2016, 3:27 PM
Megatron
Megatron - avatar
0
Why do you sum diagonal like this: sum+=(ar[i][i]+ar[i][m-1-i]); ? sum+=ar[i][i]; is sufficient.
8th Nov 2016, 2:13 PM
Sel
Sel - avatar