struct CircularBuffer{
  CircularBuffer(size_t size);
  void addElement(float newElement);
  float average();
  
  float* array;
  float* next;
  size_t size;
  int index = 0;
  int num_elements = 0;
};

CircularBuffer::CircularBuffer(size_t arraySize)
{
  size = arraySize;
  array = new float[arraySize];
  next = &array[0];
}

void CircularBuffer::addElement(float newElement)
{
  *next = newElement;
  index++;
  if (index >= size)
  {
    index = 0;
  }
  next = &array[index];
  if(++num_elements > size)
  {
    num_elements = size;
  }
}

float CircularBuffer::average()
{
  float average = 0;
  for(int i = 0; i < num_elements; i++)
  {
    average += array[i];
  }
  return average/num_elements;
}

CircularBuffer myBuffer(4);  // create a 10 element (float) circular buffer

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  if(Serial.available())
  {
    myBuffer.addElement(Serial.parseFloat());
    for(int i = 0; i < myBuffer.num_elements; i++)
    {
      Serial.print(myBuffer.array[i]);
      Serial.print(',');
    }
    Serial.println();
    Serial.print("Average: ");
    Serial.println(myBuffer.average());
  }
}