Answer to Question #332218 in C++ for Ashiir

Question #332218

Write a C++ program that creates an array “A” having 5 elements (in the main function). Then,


the program asks the user to enter values in this array. After that, the program should ask


question from user are you wanted to sort ascending or descending order kindly enter your


choice that’s you want to search in the array, also compute the sum of array for the ascending


order and difference of array for the descending order.

1
Expert's answer
2022-04-22T13:30:41-0400
#include <iostream>
#include <algorithm>

using namespace std;

void Menu()
{
	cout << "Please, choose some of the following:"
		<< "\nA - Sort in ascending order"
		<< "\nD - Sort in descending order";
	cout << "\nYour choice: ";
}

bool Descending(int a, int b)
{
	if (a > b)
		return true;
	else
		return false;
}

int main()
{
	const int N = 5;
	int A[N];
	cout << "Please, enter 5 values of an array: ";
	for (int i = 0; i < N; i++)
	{
		cin >> A[i];
	}
	cin.ignore(256, '\n');
	char choice;
	Menu();
	cin >> choice;
	switch (choice)
	{
		case 'A':case 'a':
		{
			sort(&A[0], &A[N]);
			double sum = 0;
			for (int i = 0; i < N; i++)
			{
				sum+= A[i];
				cout<<A[i]<<" ";
			}
			cout << "\nThe sum of an array is " << sum;
			break;
		}
		case 'D':case 'd':
		{
			sort(&A[0], &A[N],Descending);
			double dif = A[0];
			for (int i = 0; i < N; i++)
			{
				if(i!=0)
					dif -= A[i];
				cout << A[i]<<" ";
			}
			cout << "\nThe differnce of an array is " << dif;
			break;
		}
	}
}

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
APPROVED BY CLIENTS