The average, also known as the mean, of a sequence of numbers is calculated as follows:
Each version of the problem will require a variable, called an accumulator, to maintain a running total of the numbers entered in the loop: sum += number
. Remember to initialize this variable to 0 before entering the loop.
The while and do-while versions will also require a variable to count how many values the user enters. Whenever a user is allowed to enter data and may choose to end the input without entering any data, there must be some way that the function can indicate this situation to the client (i.e., to the code that calls the function), which these functions do by returning a -1 (which is not a valid average for a sequence of non-negative numbers).
The for-loop solution is straightforward and too simple to provide any hints beyond those appearing above.
There are at least two ways to approach this problem. The first approach requires two separate prompt/read operations. The first prompt and read operation occurs before entering the loop, ensuring that the input variable is initialized before the loop test runs. The second prompt and read operation occurs inside the loop, allowing the user to enter multiple numbers, including the value ending the loop.
The second approach uses an infinite loop with a test inside the loop, which breaks out of the loop when the test is true. The amount of code needed for either solution is about the same, so it's largely a matter of personal taste as to which approach is best.
The do-while version addresses the trade-offs appearing in the two while versions outlined above. Moving the test to the bottom of the loop allows a solution with a single prompt and read operation (like while-loop version 2) without requiring a nested if-statement (like while-loop version 1). However, after the do-while loop has finished, it requires some rather "tricky" adjustments of the number-count variable and the running total or accumulator variable.