Trying to calculate the Difference in the sum of left diagonal and right diagonal of a 2-D array. This is the code that I wrote and it is working but not giving the correct results. The right diagonal sum is working properly but the left diagonal sum keeps coming out to be 0.
This is a problem from the HackerRank algorith section "Diagonal Difference"
You have more wrong with the left diagonal the just "g=0". After a few tries I discovered that the inner for loop never executed. I am using this as a something to work with:
Now the right diagonal goes from R0C0 to R4C4 just fine. Keep in mind though that the left diagonal should go from R0C4 to R4C0 and the for loop should account for this. Now the first solution I came up with is:
1 2 3 4 5 6
int row{0};
for (int col = n - 1; col > -1;)
{
sum2 += a[row++][col--];
}
note the n - 1 or it would not catch col 0 and would through the loop off by 1. I changed the variable names to make it easier to understand.
Hope that helps,
Andy
Edit: Also found this to work"
1 2 3 4
for (int col = n - 1, row = 0; col > -1; col--, row++)
{
sum2 += a[row][col];
}