Google News
logo
C++ Program to Find Second Largest Element in an Array
In the following example of C++ program to Find the Second Largest Element in an Array :
Program :
#include <iostream>
#include <limits>

int main() {
    const int SIZE = 5;
    int arr[SIZE];
    std::cout << "Enter " << SIZE << " integers: ";
    for (int i = 0; i < SIZE; i++) {
        std::cin >> arr[i];
    }
    int largest = arr[0];
    int second_largest = arr[0];
    for (int i = 1; i < SIZE; i++) {
        if (arr[i] > largest) {
            second_largest = largest;
            largest = arr[i];
        } else if (arr[i] > second_largest && arr[i] != largest) {
            second_largest = arr[i];
        }
    }
    std::cout << "The second largest element in the array is " << second_largest << std::endl;
    return 0;
}
Output :
Enter 5 integers: 3
7
14
18
31
The second largest element in the array is 18
* This program is similar to the previous program to find the largest element in an array, but it keeps track of two variables instead of one: largest and second_largest.

* The program first initializes both variables to the first element of the array arr[0]. It then uses a for loop to iterate over each element of the array starting from the second element arr[1].

* For each element arr[i], the program checks whether it is greater than largest. If it is, the program updates both largest and second_largest. If it is not greater than largest, but it is greater than second_largest and not equal to largest, then the program updates only second_largest.

* After the loop completes, second_largest will contain the second largest element in the array. Finally, the program outputs the second largest element to the console using std::cout.