Program : Find the second largest element in an array in C++.
Solution :
#include <iostream> using namespace std; int findSecondLargest(const int array[], int size) { int largest = array[0]; int secondLargest = array[0]; for (int i = 1; i < size; i++) { if (array[i] > largest) { secondLargest = largest; largest = array[i]; } else if (array[i] > secondLargest && array[i] < largest) { secondLargest = array[i]; } } return secondLargest; } int main() { const int MAX_SIZE = 100; int size, i, secondLargest; int arr[MAX_SIZE]; cout << "Enter the size of the array: "; cin >> size; cout << "Enter the elements of the array: "; for (i = 0; i < size; i++) cin >> arr[i]; secondLargest = findSecondLargest(arr, size); cout << "The second largest element in the array is: " << secondLargest; return 0; }
Output :
Enter the size of the array: 8 Enter the elements of the array: 5 9 2 7 3 6 8 4 The second largest element in the array is: 8
Dry Run :
Let’s walk through the code written inside the findSecondLargest() function with the following inputs:
- Array: [5, 9, 2, 7, 3, 6, 8, 4]
i | i<size | array[i] | largest | secondLargest | i++ |
0 | True | 5 | 5 | 5 | 1 |
1 | True | 9 | 9 | —– | 2 |
2 | True | 2 | ——- | —– | 3 |
3 | True | 7 | ——- | 7 | 4 |
4 | True | 3 | ——- | —– | 5 |
5 | True | 6 | ——- | —– | 6 |
6 | True | 8 | ——- | 8 | 7 |
7 | True | 4 | ——– | —– | 8 |
8 | False | ——- | ——– | —– | —– |
The second largest element in the array is 8.
Want to practice more problems involving Array 1-D ? Click here.