Open In App

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

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Initialize two variables, first and second, to the minimum possible value to keep track of the largest and second largest elements in the array.
  • Start traversing the whole array using a loop.
  • For each element in the array, check if it is greater than the current largest element (first).
  • If it is greater, then update the second largest element (second) to be the current largest element, and update the largest element to be the current element.
  • If the current element is not greater than the largest element but is greater than the second largest element, then update the second largest element to be the current element.

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

C++




// 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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads