# How to calculate mode?

Hi All! I want to calculate the mode of 20 values my echo-sensor has given me. However, I have no idea how to calculate this. Do I actually have to download a certain library for this, or is there a little coding trick I can do to calculate it? The looping code is pasted here, if that helps.

``````if (start == true) {
for (i = 0; i < 20; i++) {
digitalWrite(trigEcho, LOW);
delay(2);

digitalWrite(trigEcho, HIGH);
delay(10);
digitalWrite(trigEcho, LOW);

time = pulseIn(Echo, HIGH);
distance= time*0.0343/2;

Serial.println(distance);
}
``````

How would you calculate it with a pencil and paper given 20 values ?

Put the values in an array. Sort the array. Take the mean of elements 9 and 10.

Thank you guys for your help! I made a mistake in the forum post though.. What I need to calculate is actually the mode instead of the median. I always mix those up haha...

I think calculating the mode is way too difficult compared to the level that I am at rn though. Someone else has asked this once and I would have to use an array of 8-bit unsigned integers. I have no clue what this means so I'll probably just filter out outliers by hand another way.

I want to calculate the mode of 20 values my echo-sensor has given me.

The mode is a statistical term that refers to the most frequently occurring number found in a set of numbers.

First, you'll need an array to hold your 20 values.

Then you'll want to essentially brute-force your way through the values in the array:

``````valcount = 0;
modeguess = 0; // unlikely number.
valmax = 0;
for (thisval in 20values) {
valcount = countOcurrances(thisval);
if valcount > valmax  {  // new max?
modeguess = thisval;
valmax = valcount;
}
}
``````

Use the raw pulsein times rather than the calculated distances; it'll be faster that way, probably.