Find smallest and largest element from square matrix diagonals | Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; Condition for principal diagonal ; take new smallest value ; take new largest value ; Condition for secondary diagonal ; take new smallest value ; take new largest value ; Declare and initialize 5 X5 matrix
function diagonalsMinMax ( mat ) { let n = mat . length ; if ( n == 0 ) return ; let principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; let secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { for ( let j = 1 ; j < n ; j ++ ) { if ( i == j ) { if ( mat [ i ] [ j ] < principalMin ) { principalMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > principalMax ) { principalMax = mat [ i ] [ j ] ; } } if ( ( i + j ) == ( n - 1 ) ) { if ( mat [ i ] [ j ] < secondaryMin ) { secondaryMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > secondaryMax ) { secondaryMax = mat [ i ] [ j ] ; } } } } document . write ( " " + principalMin + " " ) ; document . write ( " " + principalMax + " " ) ; document . write ( " " + secondaryMin + " " ) ; document . write ( " " + secondaryMax + " " ) ; } let matrix = [ [ 1 , 2 , 3 , 4 , - 10 ] , [ 5 , 6 , 7 , 8 , 6 ] , [ 1 , 2 , 11 , 3 , 4 ] , [ 5 , 6 , 70 , 5 , 8 ] , [ 4 , 9 , 7 , 1 , - 5 ] ] ; diagonalsMinMax ( matrix ) ;