Efficiently compute sums of diagonals of a matrix | A simple Javascript program to find sum of diagonals ; Condition for principal diagonal ; Condition for secondary diagonal ; Driver code
const MAX = 100 ; void printDiagonalSums ( mat , n ) { let principal = 0 , secondary = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) { if ( i == j ) principal += mat [ i ] [ j ] ; if ( ( i + j ) == ( n - 1 ) ) secondary += mat [ i ] [ j ] ; } } document . write ( " " + principal + " " ) ; document . write ( " " + secondary + " " ) ; } let a = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] ; printDiagonalSums ( a , 4 ) ;