468,496 Members | 1,799 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,496 developers. It's quick & easy.

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 13580
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

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Building Blocks | last post: by
14 posts views Thread by delerious | last post: by
5 posts views Thread by mp141 | last post: by
4 posts views Thread by Jan Szymczuk | last post: by
1 post views Thread by Sam | last post: by
6 posts views Thread by PyPK | last post: by
3 posts views Thread by Carles Company Soler | last post: by
6 posts views Thread by LaundroMat | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.