how do i calculate the average of an array within a function

int numbers = 10;
float [] x = new float[numbers];
float f = 0;

void setup() {
void populate() {
    for (int i = 0; i < numbers; i++) {
    float x = int(random (0,100));

this is what i have so far and i have the task of finding the average of the array using a float variable, how do i do this?? i can't figure it out for the life of me.


  • edited July 2014

    Please, when posting code, highlight it and hit CTRL+K in order to format it for the forum here! [-(

    // how-do-i-calculate-the-average-of-an-array-within-a-function
    static final float arrayAverage(float... arr) {
      float sum = 0;
      for (float f: arr)  sum += f;
      return sum/arr.length;
  • thanks, sorry its my first time posting and i was rushing, i dont want it to return the value of the average i just want it to save the average

  • edited July 2014 Answer ✓

    ... I just want it to save the average.

    I don't get it. Either you want the final average or the early sum:

    return sum/arr.length; // returns array's sum average.
    return sum; // returns array's sum.

Sign In or Register to comment.