Reputation: 27
So Im doing exercise where I have to ask the user to input the number of pancakes eaten by 10 people, print out who ate the most pancakes and then organize the list from greatest to smallest, basically I have to print out:
Person 3: Ate 10 pancakes , Person 5: Ate 9 pancakes ,Person 8: Ate 8 pancakes
However after using bubble sort I cant match the person with the right value, because bubble sort swaps them! Does anyone know of any way to fix this? For example is there another way to organize the values in an array without using bubble sort?
void getPancakes()
{
int x = 0;
int temp;
for(int y = 0; y < 10; y++)
{
++x;
cout << "How many pancakes did person " << x << " eat?" << endl;
cin >> pancakes[y];
}
}
void displayArray(int theArray[],int sizeOfArray)
{
int temp;
int i,j;
int q = 10;
for(i = 0; i <= sizeOfArray - 1 ; i++)
{
for(j = i+1 ; j < sizeOfArray ; j++)
{
if(theArray[i] < theArray[j])
{
temp = theArray[i];
theArray[i] = theArray[j];
theArray[j] = temp;
}
}
}
cout << endl;
for(i = 0; i < 10; i++)
cout << "Person " << i+1 << " ate " << theArray[i] << " pancakes" << endl;
}
Upvotes: 2
Views: 14481
Reputation: 462
Like Cody said, you'll have to store both values. As @HgMs indicated you could you a class, or a struct
, which is a class with only public data members. Here's an example:
struct person{
int id;
int pancakes;
};
int main(){
const int totalPeople = 10;
person personArray[totalPeople];
for (int i = 0; i < totalPeople; ++i){
cout << "How many pancakes did person " << i << " eat? ";
personArray[i].id = i;
cin >> personArray[i].pancakes;
}
for (int i = 0; i < totalPeople; ++i){
cout << "id: " << personArray[i].id << "\t" << "Pancakes eaten: " << personArray[i].pancakes << endl;
}
return 0;
}
You can then iterate over the array and look at the number of pancakes each person has eaten using the '.'
to access the property.
EDIT: A bubble sort would work fine.
Upvotes: 2