Diagonal Difference Hackerrank Problem coderinme

Diagonal Difference

Given a square matrix of size N X N, calculate the absolute difference between the sums of its diagonals.

Input Format

The first line contains a single integer, N. The next N lines denote the matrix’s rows, with each line containing N space-separated integers describing the columns.

Output Format

Print the absolute difference between the two sums of the matrix’s diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Explanation

The primary diagonal is:
11
5
-12

Sum across the primary diagonal: 11 + 5 – 12 = 4

The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 – 19| = 15

I Method

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n,sum1=0,sum2=0; 
    scanf("%d",&n);
    int a[100][100];
    for(int a_i = 0; a_i < n; a_i++){
       for(int a_j = 0; a_j < n; a_j++){
          
          scanf("%d",&a[a_i][a_j]);
       }
    }
	for(int a_i = 0; a_i < n; a_i++){
       for(int a_j = 0; a_j < n; a_j++){
        if(a_i==a_j){
		sum1= sum1+a[a_i][a_j];
		sum2= sum2+a[a_i][n-1-a_j];  
       }
	   }
	  
    }
	printf("%d", abs(sum1-sum2));
    return 0;
}

II Method with pointer dynamic array

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n,sum1=0,sum2=0; 
    scanf("%d",&n);
    int *a = (int *) malloc(n*n*sizeof(int));
    //int a[100][100];
    for(int a_i = 0; a_i < n; a_i++){
       for(int a_j = 0; a_j < n; a_j++){
          
          scanf("%d",&*(a+n*a_i+a_j));
       }
    }
	for(int a_i = 0; a_i < n; a_i++){
       for(int a_j = 0; a_j < n; a_j++){
        if(a_i==a_j){
		sum1= sum1+*(a+n*a_i+a_j);
		sum2= sum2+*(a+n*a_i+(n-1-a_j));  
       }
	   }
	  
    }
	printf("%d", abs(sum1-sum2));
    return 0;
}

Diagonal Difference

Competitive coding
Hackerrank problem

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.