# How do i find an average value from an array?

Hi guys

As stated as above , what is the correct code for finding an average value from an array function ? I would need to feed in 50 different analogue values i received from my sensor and stored it into the array. From the array , i would need to sum all the values up and find the average . Sry for my bad language in english and my weak coding skills . I really need help in this tks!

The usual way - add them all up and divide by the number of items. Make sure the variable you hold the sum in is big enough.

To add all the values of the array together into a variable you can use a for loop. ;) then you just need to divide the total by the number of elements inside your array...

``````float average (int * array, int len)  // assuming array is int.
{
long sum = 0L ;  // sum will be larger than an item, long for safety.
for (int i = 0 ; i < len ; i++)
sum += array [i] ;
return  ((float) sum) / len ;  // average will be fractional, so float may be appropriate.
}
``````

If you know you need the average, why wouldn't you maintain a running average as the values are read in from the sensors? You could still save them in the array, but why read them a second time?

maybe my statistics lib can help - http://playground.arduino.cc/Main/Statistics -