I am working on the second part of the Pancake Glutton exercise here: http://www.cplusplus.com/forum/articles/12974/ and for some reason I am unable to obtain the smallest value in the array. I've gone through many of the threads here in the forums but none of the solutions met my needs. I understand that I could use sort() but I want to know why my current code is not working so that I can figure out what I am doing wrong. Thank you.
//Pancake Glutton
#include <iostream>
usingnamespace std;
int main()
{
int person[10] = {0};
int i = 0;
int largestNum = person[0];
int smallestNum = person[0];
do
{
cout << "enter the amount of pancakes eaten by "
<< "person number " << i+1 << ":\t";
cin >> person[i];
cout << endl;
if (person[i] > largestNum)
largestNum = person[i];
if (person[i] < smallestNum)
smallestNum = person[i];
i++;
} while (i <= 9);
cout << "\nlargest amnt is: " << largestNum;
cout << "\nSmallest amnt is: " << smallestNum;
for (i=0; i <= 9; i++)
{
if (largestNum == person[i])
cout << "\nThe person that ate the most was "
<< "person #" << i << " with " << largestNum
<< " pancakes" << endl;
}
return 0;
}
I believe your algorithm is fine. The problem is that you are initializing smallestNum to zero. No person is able to eat less than zero pancakes, so smallestNum always remains zero. Try initializing it to some big value, like 20000 or something, and see if this solves your problem.
You are right and I realized that just before reading your post lol. I initialized it to 5000 and it worked. However, would that be a standard response for a situation like this? Or would the use of sort() be the actual standard? Thanks for your help.
I believe the standard response to find minimum and maximum elements of an array would be your algorithm with the exception that the variables holding min and max should be initialized to an element of the array. for example you could do it like this:
@kenpo - Thanks for the info. I wasn't trying to reinvent the wheel per se so much as I was trying to create a response using the required parameters of the problem. Despite this, I should start using library functions anyway since that is how it will be done in a professional environment
@m4ster r0shi & firedraco - I had it initialized to the array in the beginning but I foolishly did so before any values were entered into the array, resulting in the 0 value for smallestNum