# C++ program to sort an array in descending order using class

Submitted by Shubh Pachori, on August 13, 2022

## Problem statement

Given an array, we have to sort it in descending order using the class and object approach.

Example:

```Input:
array[0]: 22
array[1]: 1
array[2]: 44
array[3]: 5
array[4]: 33

Output:
Sorted Array is 44 33 22 5 1
```

## C++ code to sort an array in descending order using class and object approach

```#include <iostream>
using namespace std;

// create a class
class Array {
// private data member
private:
int array[5];

// public functions
public:

// getArray() function to get the value of the array
void getArray() {
for (int index = 0; index <= 4; index++) {
cout << "array[" << index << "]:";
cin >> array[index];
}
}

// putArray() function to print the array
void putArray() {
for (int index = 0; index <= 4; index++) {
cout << array[index] << " ";
}
}

// sortDescending() function to sort the array in
// descending order
void sortDescending() {
// initialising int type variables to
// perform operations
int index_1, index_2, temp;

// for loop to read the whole array
for (index_1 = 0; index_1 <= 4; index_1++) {

// for loop to compare numbers of array
for (index_2 = 0; index_2 < 4 - index_1; index_2++) {

// if condition to check if the next term
// is greater than
// this then swapping takes place
if (array[index_2] < array[index_2 + 1]) {

//  swapping numbers if numbers
//  are not in the order
temp = array[index_2];
array[index_2] = array[index_2 + 1];
array[index_2 + 1] = temp;
}
}
}
}
};

int main() {
// create a object
Array A;

// function is called by the object to
// store the array
A.getArray();

// sortDescending() function is called by the
// object to find the
// sort the array in descending order
A.sortDescending();

cout << "Sorted Array is ";

// putArray() function is called to
// print the array
A.putArray();

return 0;
}
```

### Output

```array[0]: 44
array[1]: 66
array[2]: 5
array[3]: 444
array[4]: 33
Sorted Array is 444 66 44 33 5
```

### Explanation

In the above code, we have created a class Array, one int type array data member array[5] to store the values, and public member functions getArray(), putArray(), and sortDescending() to store the given values in an array, to print the whole array and to sort the array in descending order.

In the main() function, we are creating an object A of class Array, reading integer values by the user of the array using the getArray() function, and finally calling the sortDescending() member function to sort the given array. The sortDescending() function contains the logic to sort the given array in descending order and printing the result using putArray() function.