Problem with array comparison

Hi! I'm trying to write the program suggested here, "Pancake Glutton": http://www.cplusplus.com/forum/articles/12974/.

I'm trying to make it so that the user enters a number for each entry of a size 10 array, and then the entry with the largest number is displayed.

However, if for example I enter 1, 2, 3, 4, 55, 6, 7, 8, 9, 10 as the array entries, the program states that the 10th entry holds the largest value rather than the 5th one.

Could you help?

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>;

int main()
{
	int eat [10];
	std::cout << "We will now compare how many pancakes each person ate." << std::endl << std::endl;
	for (int x = 1; x <= 10; x++)
	{
		std::cout << "Please enter how many pankcakes person " << x << " ate. ";
		std::cin >> eat[x-1];
	}

	int max = eat[0];

	for (int y = 0; y < 9; y++)
	{
		if ((eat[y] < eat[y + 1]) && (eat[y + 1] > max))
		max = y + 2;
	}

	std::cout << std::endl << "Thank you. Person " << max << " ate the most pancakes.";

	return 0;
}
I think you really need to check your logic on lines 17 and 18. What are you actually trying to do with that loop? Then try to describe what your logic is actually doing. I think you'll find a difference, or at least figure out what you actually want.
Hi! Thanks for your answer - I think I figured it out.

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
#include <iostream>;

int main()
{
	int eat [10];
	std::cout << "We will now compare how many pancakes each person ate." << std::endl << std::endl;
	for (int x = 1; x <= 10; x++)
	{
		std::cout << "Please enter how many pankcakes person " << x << " ate. ";
		std::cin >> eat[x-1];
	}

	int max = 0;
	int pcake = eat[0];

	for (int y = 0; y < 9; y++)
	{
		if ((eat[y] < eat[y + 1]) && (eat[y + 1] > pcake))
		{
			pcake = eat[y + 1];
			max = y + 2;
		}
	}

	std::cout << std::endl << "Thank you. Person " << max << " ate the most pancakes.";

	return 0;
}
You can make it so much simpler by simply getting rid of 'pcake' variable and setting max equal to the index 'y' +1.

The whole thing can be condensed down to:

1
2
3
4
5
int max = eat[0];

	for (int y = 0; y < 10; y++)
	        if ((eat[y] > max))
		         max = y+1;


Notice the shortened if-condition. Also, the for-loop will go from 0 to <10, NOT 0 to <9.
Last edited on
Topic archived. No new replies allowed.