Beginner exercises:Pancake Glutton

Hi, cant figure this out.
Instead of number which person eaten most pancakes i get number -858993460
This exercise is from this site:

http://www.cplusplus.com/forum/articles/12974/

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
33
34
35
36
  int main()
{
	int a;
	int high = 0;
	int people[10];
	int index;

	cout << "enter number of eatean pankakes by 10 different people" << endl;


	for (int n = 0; n <= 10; n++)
	{
		cin >> a;
		people[n] = a;
	}
	for (int n = 0; n <= 10; n++)
	{
		if (people[n] > high)
			high = people[n];

	}
	for (int n = 0; n >= 10; n++)
	{
		if (high == people[n])
		{
			index = n;
		}

	}
	
	
	 

	cout << "most pankakes eaten person " << index << "and it was" << high << endl;
    return 0;
}
mmm, pancakes.

int people[10];
int index;

for (int n = 0; n <= 10; n++)
{
This is an error.
people has 10 things. 0,1,2,3,4,5,6,7,8,9...
but n has 11, 0,1,2,3,4,5,6,7,8,9,10

it is highly likely to be at least part of your woes. Make it <10.
and make 10 a constant or something, don't type 10 all over the code, then you can change it once safely if you want to run with 25 people later.

going out of bounds on pointers and arrays is 'undefined'.
its actually pretty well defined; almost all compilers just access the next chunk of memory, which will either crash or not, depending on whether it belongs to your program in the OS or not, usually it does belong to it when off by 1. Unfortunately, this means it usually just runs (incorrectly but without a crash) and produces garbage. Compilers and debuggers can warn you about this, but when running it, you just get junk.



Last edited on
also the third loop does nothing, because the condition n >= 10; is false with n initialized to 0.
Topic archived. No new replies allowed.