I'm learning C++ currently and wanted to do the following exercise: Requires:
variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays
Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10) Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast.
★ Modify the program so that it also outputs which person ate the least number of pancakes for breakfast.
★★★★ Modify the program so that it outputs a list in order of number of pancakes eaten of all 10 people. i.e. Person 4: ate 10 pancakes Person 3: ate 7 pancakes Person 8: ate 4 pancakes ... Person 5: ate 0 pancakes
Sofar I've gotten the "ate most" and "second most", but I get a problem with the "least" part...
Here is my code:
#include <iostream>
using namespace std;
int arrayPersonsPancakes[]={};
int arrayPersonsNr;
int createArrayforPersons();
void pancakesPerPerson(int);
void whoAteTheMost();
int main(){
int arrayPersonsNr = createArrayforPersons();
pancakesPerPerson(arrayPersonsNr);
whoAteTheMost();
/*for(int i=0; i < arrayPersonsNr; i++){
cout << arrayPersonsPancakes[i] << endl;
}*/
}
int createArrayforPersons(){
cout << "Please enter the Nr. Of Persons who ate breakfast: " << endl;
int nrOfPersons;
cin >> nrOfPersons;
arrayPersonsPancakes[nrOfPersons];
return nrOfPersons;
}
void pancakesPerPerson(int nrOfPersons){
for (int i=0; i < nrOfPersons; i++){
cout << "Please enter how many pancakes person Nr." << i+1 << " ate: " << endl;
cin >> arrayPersonsPancakes[i];
}
}
void whoAteTheMost(){
int theMost= arrayPersonsPancakes[0];
int theSecondMost;
int theLeast;
for(int i = 0; i < arrayPersonsNr; i++){
if (arrayPersonsPancakes[i] > theMost){
theSecondMost = theMost;
theMost = arrayPersonsPancakes[i];
}
}
theLeast = theMost;
cout << theLeast << endl; //Here I get the normal output
for(int y = 0; y < arrayPersonsNr; y++){
if (theLeast > arrayPersonsPancakes[y]) {
theLeast = arrayPersonsPancakes[y];
}
}
cout << "after for " << theLeast << endl; //I always get a zero here after the loop and have no idea why.
}
for(int j = 0; j < arrayPersonsNr; j++){
if (arrayPersonsPancakes[j] == theMost){
cout << "Person Nr." << j+1 << " ate the most Pancakes: " << theMost << endl;}
else if (arrayPersonsPancakes[j] == theSecondMost){
cout << "Person Nr." << j+1 << " ate the second most Pancakes: " << theSecondMost << endl;}
else if (arrayPersonsPancakes[j] == theLeast){
cout << "Person Nr." << j+1 << " ate the least Pancakes: " << theLeast << endl;}
}
}
After the Loop for "theLeast" I always get a zero no matter what I do. I'd appreciate any comments to how I code and how I can improve that (regardless of missing comments currently, sorry about that)
Thank you!