471,831 Members | 1,294 Online

# How to calculate mode

Hi there, I don't know if the answer to this has been posted before, but I'm having some problem calculating the Mode for a dynamic array in C++.

>
cout << "Enter the size of your array: ";
cin >> aSize;
int *newArray = new int[aSize];
runMode(newArray, aSize);
< this isi in my main
--------------------------------------
void runMode( int intArray[], int arraySize )
{
cout << "Enter in the numbers: ";
for (int i = 0; i < arraySize; i++)
{
cin >> intArray[i];
}//for loop for putting numbers into the array

}// runMore function

and that's the function I'm using, any ideas on how to calculate mode would be appreciated.
Thanks
Oct 5 '06 #1
3 13910
tyreld
144 100+
First start by sorting the array. Then loop through the array keeping track of the current number and how many times it appears. If it is more then then the previously most seen number update that value.

Here is some psuedo code.

Expand|Select|Wrap|Line Numbers
1. sort ARRAY
2.
3. num = 0
4. count = 0
5. max = 0
6. mode = 0
7.
8. for each i in ARRAY do
9.
10.   if num not equal to ARRAY[i] then
11.     num = ARRAY[i]
12.     count = 1
13.
14.   else
15.     count++
16.
17.   endif
18.
19.   if count > max then
20.     max = count
21.     mode = num
22.
23.   endif
24.
25. next
26.
Oct 5 '06 #2
Thank you so much :o)
Oct 11 '06 #3
Be aware that there can be more than one mode in a dataset.

JT
Jul 23 '07 #4