top of page

Cocubes Coding | Second largest number

Updated: Jun 13, 2020

In this blog, we will learn to find the second largest number in an array of integers.


Input:

The first line contains an integer T, a total number of elements.

Then follow T integers.


Output:

Display the second largest among the given T integers.

Constraints:

1 <= T <= 1000

1 <= integers <= 1000000


Sample Input and Output:


Input:

7
23 45 7 34 25 25 89

Output:

45

Implementation using C:

#include <stdio.h> 
#include <limits.h>  
  
void print_sec_largest(int arr[], int arr_size) 
{ 
 int i, first, second; 
 
 if (arr_size < 2) 
 { 
 printf(" Invalid Input "); 
 return; 
 } 
  
 first = second = INT_MIN; 
 for (i = 0; i < arr_size ; i ++) 
 { 
 if (arr[i] > first) 
 { 
 second = first; 
 first = arr[i]; 
 } 
 else if (arr[i] > second && arr[i] != first) 
 second = arr[i]; 
 } 
 if (second == INT_MIN) 
 printf("There is no second largest element\n"); 
 else
 printf("The second largest element is %d \n", second); 
} 

int main() 
{ 
 int n;
 scanf("%d",&n);
 int arr[n];
 for(int i=0; i<n; i++)
 {
  scanf("%d",&arr[i]);
 }
 print_sec_largest(arr, n); 
 return 0; 
}
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

38 views0 comments

Recent Posts

See All
bottom of page