Find Second largest element in an array | C ++ program to find second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; find the largest element ; find the second largest element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int largest = second = INT_MIN ; for ( int i = 0 ; i < arr_size ; i ++ ) { largest = max ( largest , arr [ i ] ) ; } for ( int i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] != largest ) second = max ( second , arr [ i ] ) ; } if ( second == INT_MIN ) printf ( " There ▁ is ▁ no ▁ second ▁ largest ▁ element STRNEWLINE " ) ; else printf ( " The ▁ second ▁ largest ▁ element ▁ is ▁ % d STRNEWLINE " , second ) ; } int main ( ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; print2largest ( arr , n ) ; return 0 ; }