Diagonal sum
Code
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n; //matrix size
cin>>n;
int a[n][n]; //the matrix
for(int i=0;i<n;i++){ //rows
for(int j=0;j<n;j++){ //columns
cin>>a[i][j];
}
}
int sum1=0; //to store sum of left diagonal
int sum2=0; //to store sum of right diagonal
for(int i=0;i<n;i++){ //calculates sum of left diagonal
for(int j=0;j<n;j++){
if(i==j){
sum1=sum1+a[i][j];
}
}
}
int j=n-1;
for(int i=0;i<n;i++){ //calculates sum of left diagonal
sum2=sum2+a[i][j];
j--;
}
int diff=abs(sum1-sum2); //absolute difference between two diagonals
cout<<diff; //print the difference
return 0;
}
0 Comments