C++ Program to sort an array in descending order


In this program, You will learn how to sort an array in descending order in C++.


An array list is: 2 3 1 7 6

After sort: 7 6 3 2 1

Example: How to sort an array in descending order in C++.

#include<iostream>
using namespace std;

int main() {

    int a[10];
    int n, temp;

    cout << "Enter size of an array:";
    cin>>n;

    cout << "Enter array elements:";
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    for (int i = 0; i < n; i++) {
        for (int j = 1 + i; j < n; j++) {
            if (a[i] < a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    cout << "Array list in descending order:";
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:20 10 30 40 50
Array list in descending order:50 40 30 20 10