# Sum of diagonal

Practice

Author: Anurag
Tester: Anurag
Editorialist: Anurag

# DIFFICULTY:

EASY,MEDIUM,GREEDY,STRING,CAKEWALK, SIMPLE

Math ,String

# PROBLEM:

Chef is very clever that’s why his mother given him a square matrix and told him to calculate the absolute difference between the sums of its diagonal .

# EXPLANATION:

Since we have given a square matrix so we have to just find out both the diagonal element and sum of it later we have to find out absolute difffer between them
for example we have given a matrix of 2 x 2
1 3
2 8
here sum of main diagonal is 9 and sum of other diagonal element is 5 and the absolute differ between them is 4 hence the answer is 4

lets take another example
here N=3

``````1 2 3
4 5 6
9 8 9
``````

The sum of left to right diagonal is 1+5+9 = 15, the right to left diagonal sum is 3+5+9=17 there absolute difference is |15-17|= 2.

# SOLUTIONS:

Setter's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
int sum1=0,sum2=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j){
sum1+=a[i][j];
}
}
}
int i=0;
int j=n-1;
while(i<n && j>=0){
sum2+=a[i][j];
i++;
j–;
}
int k=abs(sum1-sum2);
cout<<k;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Tester's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
int sum1=0,sum2=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j){
sum1+=a[i][j];
}
}
}
int i=0;
int j=n-1;
while(i<n && j>=0){
sum2+=a[i][j];
i++;
j–;
}
int k=abs(sum1-sum2);
cout<<k;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}

Editorialist's Solution

#include<bits/stdc++.h>
using namespace std;
void testcase()
{
int n;
cin>>n;
int a[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
int sum1=0,sum2=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j){
sum1+=a[i][j];
}
}
}
int i=0;
int j=n-1;
while(i<n && j>=0){
sum2+=a[i][j];
i++;
j–;
}
int k=abs(sum1-sum2);
cout<<k;

}
int main()
{
int t;
cin>>t;
while(t–)
{
testcase();
cout<<endl;
}
return 0;
}