This is a C++ Program to Find the second largest/Smallest Number in an Array.
The program takes an array and finds the second largest/smallest number in it.
1. The program takes an integer array.
2. Using nested for loops, the array is first sorted.
3. Then, the second largest and second smallest element in the sorted array is printed.
4. Exit.
Here is the source code of C++ Program to Find the second largest/Smallest Number in an Array. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int A[10], n, i, j, x;
cout << "Enter size of array : ";
cin >> n;
cout << "Enter elements of array : ";
for (i = 0; i < n; i++)
cin >> A[i];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (A[i] < A[j])
{
x = A[i];
A[i] = A[j];
A[j] = x;
}
}
}
cout << "Second largest number : " << A[1];
cout << "\nSecond smallest number : " << A[n - 2];
return 0;
}
1. The user is asked to enter the array size and stored in the variable ‘n’.
2. The array elements are stored in the array ‘A’.
3. Using nested for loops, the array is sorted in ascending order so that second largest/smallest numbers can be easily retrieved.
4. The result is then printed.
Case 1 : Enter size of array : 4 Enter elements of array : 150 69 741 0 Second largest number : 150 Second smallest number : 69 Case 2 : Enter size of array : 5 Enter elements of array : 26 38 75 12 91 Second largest number : 75 Second smallest number : 26 Case 3 : Enter size of array : 3 Enter elements of array : 1 2 3 Second largest number : 2 Second smallest number : 2
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Practice Computer Science MCQs
- Check C++ Books
- Check Programming Books
- Practice Programming MCQs
- Check Computer Science Books