Mode Function

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.



Here is 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
#include <iostream>

using namespace 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!
Last edited on
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.
Last edited on
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!
Topic archived. No new replies allowed.