Hey guys, I'm having a bit of a problem with figuring out how to properly write up a process to calculate the mode of an array of numbers.
Criteria of project:
In statistics the mode of a set of values is the value that occurs most often. Write a program that determines how many pieces of pie most people eat in a year. Set up an integer array that can hold responses from 30 people. For each person, enter the number of pieces they say they eat in a year (or optionally, read their responses from a text file). Then write a function that finds the mode of these 30 values. This will be the number of pie slices eaten by the most people. The function that finds and returns the mode should accept two arguments, an array of integers, and a value indicating how many elements are in the array.
#include <iostream>
usingnamespace std;
int mode(int piesAte[], int size)
{
int counter = 1;
int max = 0;
int modePie = piesAte[0];
for (int i = 0; i < size - 1; i++)
{
if (piesAte[i] == piesAte[i+1])
{
counter++;
if (counter > max)
{
max = counter;
modePie = piesAte[i];
}
}
else
counter = 1;
}
return modePie;
}
int main()
{
cout << "Enter the amount of pie eaten by each person:" << endl;
int survey[30];
for(int i = 0; i < 30; i++)
{
cout << "Person " << (i + 1) << "/30 pies eaten: ";
cin >> survey[30];
}
cout << "The most eaten slice is: " << mode(survey, 30) << endl;
system("Pause");
return 0;
}
Any feedback pertaining to this project would be greatly appreciated, thanks for your time!
Multi-modal. Four persons eat. Two eat 1 and other two eat 3 each. The 1 and 3 are equally frequent.
You do need a container that has one element for each unique value (of pieces) and each element should store a count of how many persons did eat that many pieces.
Let say that the query returns {1,3,1,7,2,3,1}. The unique values are {1,2,3,7} so we have four pairs (pieces,persons):
(1,3)
(2,1)
(3,2)
(7,1)
Thus, the mode is 1.
You do write to the "Generic" Forum, so I assume that you are past the beginner phase and can use the std::map as the container. Can you?
PS1. Please use the code tags when posting code.
PS2. Your main does an out-of-range error.
Unfortunately, I have yet to learn how to use the std::map in my class. So I need to figure out another method of creating a function that can calculate the mode of an array. Still thanks for the advice!