# HackerRank solution for Diagonal Difference in C++

Problem:- diagonal difference hacker rank solution in Java or diagonal difference hacker rank solution c++ or plus-minus hacker rank solution c++ or diagonal difference program in c or diagonal difference solution in c or diagonal difference hacker rank solution in python or diagonal difference in java or diagonal difference hacker rank solution in c or Hacker Rank Solution For Diagonal Difference in C++ or Diagonal Difference in C++ or Hacker Rank solution for Diagonal Difference in C++.

Check This-
Hacker rank Solution for C++ Sub Domain Introduction, Classes, STL, Inheritance.

Logic:- So logic is very simple in this diagonal difference hacker rank problem we have to find the diagonal sum of matrix  and after find the sum just simply find out the difference between both diagonal sum and if the difference of both diagonal matrices is negative then find the Mod or in the end print the output. See the above logic solution with an example in explanation.

Explanation:- So as we already know what is the logic so without wasting time lets just implement the above logic in our diagonal difference hacker rank problem with an example. Take a MATRIX with the same number of row and column, see the example below.

Example

3          //Row and Column Size

11     2      4
4       5      6
10     8    -12

so our matrix is 3 * 3 and diagonals of the matrix are given below

First Diagonal

11
5
-12

and the sum of Diagonal is 11 + 5 + (-12) = 4

Second Diagonal

4
5
10

and the sum of second diagonal is 4 + 5 + 10 = 19

Now the last step is to find the Difference of between sum of diagonal so add first diagonal and second diagonal after that mod the difference so | 4 - 19| = 15. Hence we got our solution.

Copy the full solution or colored code and paste into the hacker rank editor and click to Run Code if the code runs successfully then click to Submit Code. Before pasting the code into the editor make sure you have chosen c++ editor in the top right drop down option.

Solution:-

#include <iostream>
using namespace std;

int main()
{
int N,lsum=0,rsum=0;

cin>>N;
int a[N][N];

for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
cin>>a[i][j];
if(i==j)
{
lsum+=a[i][j];
}
}
}
for(int i=0;i<N;i++)
{
for(int j=N-1-i;j>=0;)
{
rsum+=a[i][j];
break;
}
}
cout<<abs(lsum-rsum)<<endl;
return 0;
}

Output:-

You May Also Like