Diagonal Difference - HackerRank Solution

Given a square matrix, calculate the absolute difference between the sums of its diagonals. Diagonal Difference - HackerRank Solution

Diagonal Difference

In this post, we will be covering Diagonal Difference from hackerrank, in which we have to calculate the difference between the summation value of Diagonals. The solution is carried out in C++ with the required sets of variables, initializations, looping to get the required output.

Problem Definition

Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr is shown below:

Function Description

Complete the diagnoldifference function in the editor below.
diagonalDifference takes the following parameter:

• int arr[n][m]: an array of integers.

Return

• int: the absolute diagonal difference

Input Format

The first line contains a single integer, n, the number of rows and columns in the square matrix arr.
Each of the next n lines describes a row,arr[i] , and consists of n space-separated integers arr[i][j].

Output Format

Return the absolute difference between the sums of the matrix's two diagonals as a single integer.

3
11 2 4
4 5 6
10 8 -12
15

Let's write the code for Problem

We will be solving this problem by calculating the sum of elements present diagonally in the given square matrix and then will be finding the absolute difference of two summed values. If you do not have an idea on how to use absolute function - refer to this article on absolute function in C++

Get a clear explanation of this problem on HackerRank

Code Solution

#include <bits/stdc++.h>

using namespace std;
int main()
{
int n,s=0,c=0,d=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];
}
}
for(int i=0;i<n;i++)
{
c+=a[i][i];
}
for(int i=0;i<n;i++)
{
d+=a[i][n-1-i];
}
s=abs(c-d);
cout<<s;
return 0;
}

Sample Test Case Passed Successfully

This problem and its description are taken from HackerRank - Solution is provided by The Coding Bro in sole purpose of Learning and Education - Visit HackerRank to solve more problems.

If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.

Thanks from my side, this is Mayank, keep learning and exploring !!

Mayank Pathak is the editor and blogger at "The Coding Bro".He loves to codes, learn new technologies, and write the coding solutions and articles for the communities of learners, especiall…