Pancake glutton

I;m been trying the Beginner Exercise :
http://www.cplusplus.com/forum/articles/12974/

Heres the code
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// pancake Glutton

#include <iostream>
using namespace std;

int p[10]; 

int main ()
{
    for (int n=1; n<11; n++)
    {
        cout << "Person " << n << " ate how many pancake ?: "; 
        cin >> p[n];
    } 
    
    
    
    
    for (int n=1; n<11; n++) 
    {
        if ( p[1]> p[n])
     {
         cout << "Person 1 ate the most pancake" << endl;
         break;
     }
        else if ( p[2]> p[n])
     {
         cout << "Person 2 ate the most pancake" << endl;
         break;
     }
        else if ( p[3]> p[n])
     {
         cout << "Person 3 ate the most pancake" << endl;
         break;
     }
        else if ( p[4]> p[n])
     {
         cout << "Person 4 ate the most pancake" << endl;
         break;
     }
        else if ( p[5]> p[n])
     {
         cout << "Person 5 ate the most pancake" << endl;
         break;
     }
        else if ( p[6]> p[n])
     {
         cout << "Person 6 ate the most pancake" << endl;
         break;
     }
        else if ( p[7]> p[n])
     {
         cout << "Person 7 ate the most pancake" << endl;
         break;
     }
        else if ( p[8]> p[n])
     {
         cout << "Person 8 ate the most pancake" << endl;
         break;
     }
        else if ( p[9]> p[n])
     {
         cout << "Person 9 ate the most pancake" << endl;
         break;
     }
        else if ( p[10]> p[n])
     {
         cout << "Person 10 ate the most pancake" << endl;
         break;
     }
    }
    
    system ("pause");
    return 0;
}


and it keep saying person 2 ate the most pancake when other person ate more. I want to make program to print who ate the most pancake. So what do I need to change to make it work ?
Last edited on
You need to rethink how to find the maximum element in an array; your big for() loop is
totally wrong.
First of all, the first element of p[10] is p[0] and not p[1], and the last element of p[10] is actually p[10];
declaring int p[10] means that you are declaring an array that contains 10 integers, of indexes going from 0 to 9.
If you assign a value to p[n] when n = 10 the compiler might not give you an error, but you have no idea where the value of p[10] will be written: it may overwrite some other variable.

Also, try to use two nested for loops this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

int temp = p[0] //temp stores the max number of pancakes

for (int a=0;a<11;a++)
{
   for (int b=0;b<11;b++)
   {
      if (p[a]>p[b])
      {
          temp = p[a];
      }
    }
}

for (int a=0;a<11;a++)
{
   if (p[a] = temp)
   {
        cout << "Person " << p[a] << " ate the most pancakes\n" ;
   }
}


Topic archived. No new replies allowed.