Open In App

C++ Program to Find the Second Largest Element in an Array

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++.

Examples:



Input: 
arr[] = {34, 5, 16, 14, 56, 7, 56}

Output: 34

Explanation: The largest element is 56 and the second largest element  is 34.

Find the Second Largest Element in an Array in C++

To find the second largest element in an array in C++, we can initialize two variables, first and second, to the minimum possible value for the data type. Then, we can traverse the array and update the first and second as we find elements larger than them.

Approach

C++ Program to Find the Second Largest Element in an Array




// C++ Program to illustrate how to find the second largest
// element in an array
#include <climits>
#include <iostream>
using namespace std;
  
int main()
{
    // Initialize an array
    int array[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(array) / sizeof(array[0]);
  
    // Initialize first and second to the minimum possible
    // value
    int first = INT_MIN, second = INT_MIN;
  
    // Traverse the array
    for (int i = 0; i < n; i++) {
        // If current element is greater than first
        if (array[i] > first) {
            second = first;
            first = array[i];
        }
        // If current element is in between first and second
        else if (array[i] > second && array[i] < first) {
            second = array[i];
        }
    }
  
    // Print the second largest element
    cout << "Second Largest Element in the Array: "
         << second << endl;
  
    return 0;
}

Output

Second Largest Element in the Array: 4

Time Complexity: O(N), where N is the size of the array.
Auxiliary space: O(1)


Article Tags :