Finding the largest value

Alright, I'm trying to find the largest value through a set of numbers that the user enters. I've googled how to and looked through the forums but I don't understand why or the process of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  //Main function
int main()
{
	//List local variables
	int pancakes[10] = { 0 };
	string person[10] = { "Person 1", "Person 2", "Person 3", "Person 4",
		"Person 5", "Person 6", "Person 7", "Person 8", "Person 9", "Person 10" };
	
	//Ask how many pancakes eatten by 10 different people

	cout << "How many pancakes did " << person[0] << " eat?" << endl;
	cin >> pancakes[0];
	cout << "How many pancakes did " << person[1] << " eat?" << endl;
	cin >> pancakes[1];
	cout << "How many pancakes did " << person[2] << " eat?" << endl;
	cin >> pancakes[2];
	cout << "How many pancakes did " << person[3] << " eat?" << endl;
	cin >> pancakes[3];
	cout << "How many pancakes did " << person[4] << " eat?" << endl;
	cin >> pancakes[4];
	cout << "How many pancakes did " << person[5] << " eat?" << endl;
	cin >> pancakes[5];
	cout << "How many pancakes did " << person[6] << " eat?" << endl;
	cin >> pancakes[6];
	cout << "How many pancakes did " << person[7] << " eat?" << endl;
	cin >> pancakes[7];
	cout << "How many pancakes did " << person[8] << " eat?" << endl;
	cin >> pancakes[8];
	cout << "How many pancakes did " << person[9] << " eat?" << endl;
	cin >> pancakes[9];

	//Which person ate the most pancakes 
You've recorded the number of pancakes each person ate in the pancakes array.

Now all you have to do is iterate through that array to find the largest number. The index to that number is the person who ate the most pancakes.

BTW, lines 11-20 can be replaced with a simple loop:
1
2
3
4
    for (int i=0; i<10; i++)
    {  cout << "How many pancakes did " << person[i] << " eat?" << endl;
        cin >> pancakes[i];
    }


Last edited on
You could also use a std::map and sort it by pancakes instead of by name. :P
How do youiterate through the array? Using a for loop like
1
2
3
4
5
6
7
 
for (int i  =  0; i > 10; i++)
{
}
      for (i = 0; i < 10; i++)
           {
            }


Is that how you sort trhough it?

Last edited on
Well you shouldn't use magic numbers like 10. You should assign it to a constant variable and use that through the program.

How do you iterate through the array? Using a for loop like ...

AbstractionAnon showed you how to do the for loop for entering the information. If you are referring to finding the largest value that is very simple. Just iterate over all the elements and check if it is larger than the previous largest.
1
2
3
4
5
6
7
8
9
10
11
std::string personWhoAteMost = person[0];
int largestAte = pancakes[0];

for(int i = 1; i < numberOfPeople; ++i)
{
    if(pancakes[i] > largestAte)
    {
        largestAte = pancakes[i];
        personWhoAteMost = person[i];
    }
}

Topic archived. No new replies allowed.