C++ Program to Find Second Largest and Smallest Elements of an Array

bookmark

#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;
}

 

Output:

Enter size of array : 4
Enter elements of array : 150 69 741 0
Second largest number : 150
Second smallest number : 69