Find smallest and largest element from square matrix diagonals | CPP program to find smallest and largest elements of both 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 ; Driver code ; Declare and initialize 5 X5 matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; void diagonalsMinMax ( int mat [ 5 ] [ 5 ] ) { int n = sizeof ( * mat ) / 4 ; if ( n == 0 ) return ; int principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; int secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { for ( int 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 ] ; } } } } cout << ( " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " ) << principalMin << endl ; cout << ( " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " ) << principalMax << endl ; cout << ( " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " ) << secondaryMin << endl ; cout << ( " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " ) << secondaryMax << endl ; } int main ( ) { int matrix [ 5 ] [ 5 ] = { { 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 ) ; }