Sunday, September 25, 2016

Diagonal Summation

11 2 4
4 5 6
10 8 -12
Explanation
The primary diagonal is:  11       5             -12
Sum across the primary diagonal: 11 + 5 - 12 = 4
It may be done 2 ways:
First way:
    int total = 0;
    for (int row = 0; row < a.length; row++)
    {
        total += a[row][row];
    }
Second way:
//Logic to calculate sum of diagonal1
          int sumOfDiagonal1=0;
          for (int i = 0, j =0; i< rows && j < columns; i++, j++) {
                 sumOfDiagonal1= sumOfDiagonal1 + matrix[i][j];
                
          }
Resource Link:
https://www.hackerrank.com/challenges/diagonal-difference
http://www.javamadesoeasy.com/2015/02/find-sum-of-both-diagonals-in-matrix.html

No comments:

Post a Comment