PancakeGlutton: Output an Array in Descending Order C++.

This is the solution to PancakeGlutton exercise from cplusplus.com. Printing out an array of number in descending or ascending order can be accomplish with out doing any type of sort. ok, let’s say you want to find out how may pancakes a every person ate, and then output in descending order starting with the most pancakes. In this case the output is in descending order, so all you have to do is find the biggest number and then decrease by one and print every number in the array. Here’s an example.

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int persons[10]; 
	for(int i = 0; i < 10; i++)
	{
		cout << "Enter how many pancakes person " << i << " ate: ";
		cin >> persons[i];
	}
	//finding biggest and smallest
	int small = persons[0], big = persons[0], idSmall, idBig;
	for(int j = 0; j < 10; j++)
	{
		if(small > persons[j]) { small = persons[j]; idSmall = j; }
		if(big < persons[j]) { big = persons[j]; idBig = j; }
	}
 
	cout << "The person who ate the most pancakes > " << idBig << endl;
	cout << "The person who ate the least pancakes > " << idSmall << endl;
 
	//output in descending order starting with most pancakes
	for(big; big >= 0; big--)
	{
		for(int i = 0; i < 10; i++)
		{
		    if(persons[i] == big) { cout << "Person " << i << " ate " << big << endl; }
		}
	}
	system("pause");
	return 0;
}
Share This!

Leave a Reply

Your email address will not be published.