I am trying to refresh my knowledge of C++ basics. I found a prompt online to create a simple program that asks the user to input the number of pancakes eaten by 10 people, then sort the input and print out who ate the most/least pancakes.
When I run this code, it often prints the person who ate the least pancakes, but then prints an "Abort trap: 6" error. All other references to this error I could find involve overflowing the stack (which I don't know much about), but I don't know how I am overflowing the stack with only an array of 10 integers!
Is it a mistake I have made inputting the data, or is my sort function broken?
#include <stdio.h>
#include <iostream>
usingnamespace std;
int main()
{
int person[10];
int i;
for ( i=1; i<=10; i++)
{
cout << "Enter the amount of pancakes eaten by Person " << i << ": " ;
cin >> person[i];
}
int min;
int max;
min = person[0];
max = person[i];
for (i=1; i<=10; i++)
{
if (min>=person[i])
min=person[i];
if (max<=person[i])
max=person[i];
}
for ( i=1; i<=10; i++)
{
if(person[i]==min)
cout << "Person " << i << " ate the least pancakes: " << person[i] << endl;
if(person[i]==max)
cout << "Person " << i << " ate the most pancakes: " << person[i] << endl;
}
return 0;
}
Your problem stems from the fact you are accessing array indices out of bounds.
Arrays in C++ begin with index 0, not 1.
So instead of looping for (int i = 1; i <= 10; i++)
you should be looping:
1 2 3 4
for (int i = 0; i < 10; i++)
{
// ..
}
Second, I don't understand what you mean to do when you say
1 2
min = person[0];
max = person[i]; // (i is currently 11 here)
This seems quite error prone. I would initialize both min and max to be person[0].
1 2
min = person[0];
max = person[0];
Also, in C++ it is suggested to put variables only in the scope they are needed; your int i variable is only needed in the for loops, so I would remove its declaration at the start of the program, and only make it known to each for loop, like I did above.
Thanks! That was definitely something I forgot about when writing the initial program. I have cleared up those mistakes and made it so the output can still list the "people" as 1-10. Works like a charm now!