Find smallest and largest element from square matrix diagonals | C ++ 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 ; take new smallest value ; take new largest value ; Condition for secondary diagonal is mat [ n - 1 - i ] [ i ] 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 ; const int n = 5 ; void diagonalsMinMax ( int mat [ n ] [ n ] ) { 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 = 0 ; i < n ; i ++ ) { if ( mat [ i ] [ i ] < principalMin ) { principalMin = mat [ i ] [ i ] ; } if ( mat [ i ] [ i ] > principalMax ) { principalMax = mat [ i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] < secondaryMin ) { secondaryMin = mat [ n - 1 - i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] > secondaryMax ) { secondaryMax = mat [ n - 1 - i ] [ i ] ; } } cout << " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " << principalMin << " STRNEWLINE " ; cout << " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " << principalMax << " STRNEWLINE " ; cout << " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " << secondaryMin << " STRNEWLINE " ; cout << " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " << secondaryMax ; } int main ( ) { int matrix [ n ] [ n ] = { { 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 ) ; }