Q:

C++ program to sort an array in Descending Order

0

C++ program to sort an array in Descending Order

In this program, we will learn how to sort integer array numbers/elements in Descending Order in C++?

This program will read total number of elements (N) and check value of N must be valid between 1-N, program will read N integer values (as array elements), print input elements with sorted array element (After sorting elements in Descending Order).

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to sort array elements in Descending Order in C++

#include <iostream>
using namespace std;

#define MAX 100

int main()
{
	//array declaration
	int arr[MAX];
	int n,i,j;
	int temp;
	
	//read total number of elements to read
	cout<<"Enter total number of elements to read: ";
	cin>>n;
	
	//check bound
	if(n<0 || n>MAX)
	{
		cout<<"Input valid range!!!"<<endl;
		return -1;
	}
	
	//read n elements
	for(i=0;i<n;i++)
	{
		cout<<"Enter element ["<<i+1<<"] ";
		cin>>arr[i];
	}
	
	//print input elements
	cout<<"Unsorted Array elements:"<<endl;
	for(i=0;i<n;i++)
		cout<<arr[i]<<"\t";
	cout<<endl;
	
	//sorting - Descending ORDER
	for(i=0;i<n;i++)
	{		
		for(j=i+1;j<n;j++)
		{
			if(arr[i]<arr[j])
			{
				temp  =arr[i];
				arr[i]=arr[j];
				arr[j]=temp;
			}
		}
	}
	
	//print sorted array elements
	cout<<"Sorted (Descending Order) Array elements:"<<endl;
	for(i=0;i<n;i++)
		cout<<arr[i]<<"\t";
	cout<<endl;	
		
	return 0;	
}

Output

First run:
Enter total number of elements to read: 5
Enter element [1] 123
Enter element [2] 345
Enter element [3] 567
Enter element [4] 12
Enter element [5] 90
Unsorted Array elements:
123	345	567	12	90	
Sorted (Descending Order) Array elements:
567	345	123	90	12	

Second run:
Enter total number of elements to read: 120
Input valid range!!!

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to reverse a number... >>
<< C++ program to sort an array in Ascending Order...