Hi, there. I'm writing a program that calculates the mode, mean and median of an array of integers. I've done the mean and median but i can't figure out mode.
I have to find the number of modes.
Ex array of integers: 10, 10, 4, 5, 6,5, 6, 7
My function has to return the number 3. Because there are 3 sets of mode; 10,5,6.
How do i implement this in my function because for now it just calculates the mode. It only return the number mode 10.
#include<iostream>
#include<algorithm> //for sorting
usingnamespace std;
int getnmode(constint* a,int n)
//'a' is sorted array, n is size of array
{
int i,rep=1/*repetitions*/,maxrep=1/*repetitions of mode*/,nmode=1/* no. of modes*/;
for(i=1;i<n;++i)
{
if(a[i]==a[i-1])
//if the current number is the same as previous number, we have a repitition
{
++rep;
if(rep==maxrep){nmode++;}
//if no. of reps == no. of reps of mode, we have another mode
elseif(rep>maxrep){nmode=1;maxrep=rep;}
//if the current number has been repeated
//more than the number of times our supposed mode
//then this number (a[i]) is our new supposed mode
//all previous modes are disposed (i.e. nmode=1)
}
else rep=1;
}
return nmode;
}