functions advice/tips

Hey everyone,

I'm trying to learn more about writing functions and needed some help understanding how to implement them. I've been trying to shrink the size of my void loop() in a project of mine by rewriting some lines as functions. I figured this would also make my code more modular if I decided to turn off certain features or sensors. In particular, I need help understanding return statements. Here's a sample code that I've written:

void setup() {
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  calc_average_v();
  Serial.println(average);
  delay(1);        // delay in between reads for stability

}

int calc_average_v(){
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  return average;
}

Am I calling this function correctly and would this be better as a void or a int function? I need the value of average to be present in void loop(), but I'm confused on whether the function needs to return a value or if the code just running through the function is sufficient. I'd really appreciate any links or tutorials on understanding functions.

This is not all your code.

You need to put your returned value into a variable of some kind.
.

int myReturnAverage = calc_average_v();
Serial.println(myReturnAverage);

OR

Serial.println( calc_average_v() );
.

LarryD:
You need to put your returned value into a variable of some kind.
.

int myReturnAverage = calc_average_v();
Serial.println(myReturnAverage);

OR

Serial.println( calc_average_v() );
.

its true

// advance to the next position in the array:
readIndex = readIndex + 1;

// if we're at the end of the array...
if (readIndex >= numReadings) {
// ...wrap around to the beginning:
readIndex = 0;

Try:

readIndex = ++readIndex % numberReadings;

Edit:
Read this in your spare time:

LarryD:
You need to put your returned value into a variable of some kind.
.

int myReturnAverage = calc_average_v();
Serial.println(myReturnAverage);

OR

Serial.println( calc_average_v() );
.

Thanks for the tip, this is exactly what I need help with.

The code is based off the Arduino.cc tutorial for smoothing an analog input that I was using to get a grasp of using functions. I just included the setup, loop, and function that I tried to use:
https://www.arduino.cc/en/Tutorial/Smoothing