I was trying to solve a challenge in C on HackerRank. There is a square matrix with n rows and columns.The challenge is to print the absolute difference between the two sums of the matrix's diagonals as a single integer.
Here's the link: https://www.hackerrank.com/challenges/diagonal-difference
I'm able to get the correct answer but the printf() statement at the end of the code does not work unless I add an uecessary printf("") before the for loop statement. Could someone explain why this is happening?
Thanks in advance
Here's the code:
#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;
scanf("%d",&n);
int a[n][n],sum_d1=0,sum_d2=0,a_i,a_j;
for( a_i = 1; a_i <= n; a_i++){
for(a_j = 1; a_j <= n; a_j++){
scanf("%d",&a[a_i][a_j]);
if(a_j==a_i)
sum_d1=sum_d1+a[a_i][a_j];
}
}
printf("");// the last printf works only when this statement is present
for(a_i=1;a_i<=n;a_i++)
{
for(a_j=n;a_j>0;a_j--)
{
if((a_i+a_j)==(n+1))
sum_d2=sum_d2+a[a_i][a_j];
}
}
printf("%d",abs(sum_d1-sum_d2)); //this doesn't work if there is no printf above
retu 0;
}
