Answer to Question #144199 in C++ for ahmed

Question #144199
Write a C++ program to first allow a user to input n integer numbers into array X and then sort the contents of the array descending order and finally print on the screen both the sorted and the unsorted arrays.
1
Expert's answer
2020-11-13T16:31:17-0500
#include<iostream>


#define MAX_NUMBERS 20


int gt_compare(int a, int b){  
	return a > b; 
}


void sortArrDescendingOrder(int* a, int arr_len, int (*cmp)(int,int)){
	int tmp;
    
    for(int i = 0; i < arr_len; i++)
    	for(int j = 1; j < arr_len; j++){
    		if(cmp(a[j], a[j - 1])){
    			tmp = a[j];
    			a[j] = a[j - 1];
    			a[j - 1] = tmp;
    		}
    	}
}


int main(){


	int user_numb;


	std::cout << "Enter a size of array: " << std::endl;
	std::cin >> user_numb;


	if(user_numb < 0 || !user_numb || user_numb > MAX_NUMBERS)user_numb = MAX_NUMBERS;


    int i_arr_1[user_numb] = { 0 }, i_arr_2[user_numb] = { 0 };
    short i;


    std::cout << "Please, enter the " << user_numb << " of values: " << std::endl;


    for(i = 0; i < user_numb ; i++){
    	std::cout << "#" << i + 1 << ": ";
    	std::cin >> i_arr_2[i];


        i_arr_1[i] = i_arr_2[i];                         //saving an unsorted array
    }


    sortArrDescendingOrder(i_arr_2, user_numb, gt_compare);




    std::cout << std::endl << "The sorted array: ";


    for(i = 0; i < user_numb; i++)std::cout << i_arr_2[i] << ' ';




    std::cout << std::endl;




    std::cout << std::endl << "The unsorted array: ";


    for(i = 0; i < user_numb; i++)std::cout << i_arr_1[i] << ' ';


    std::cout << std::endl;




	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog