#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;
}
Enter 5 integers: 3
7
14
18
31
The second largest element in the array is 18
largest
and second_largest
.arr[0]
. It then uses a for
loop to iterate over each element of the array starting from the second element arr[1]
.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
.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
.