c++ loop

Write a program that calculates the average of a stream of positive numbers. The user can enter as many positive numbers as they want, and they will indicate that they are finished by entering a negative number. For this program, treat zero as a positive number, i.e., zero counts as a number that goes into the average. Of course, the negative number should not be part of the average. You must use a function to read in the numbers, keep track of the running sum and count, compute the average, and return the average to the main() function. Note that you must use a loop to do this, as you don't know how many numbers the user will enter ahead of time.



I don't you to write the whole code for me. I just want an explanation to how to go about writing it. I am having problem writing a loop program for it..
The simplest way to do it is to have three variables: justEntered, sumOfEntered and totalNumbersEntered (or whatever you want to call them, they're just so you know what they do). When they enter a number (that isn't negative), add that number to the sum, and increase numEntered by one.
When they enter a negative value, break the loop, and display (sum / numEntered). But, before you try to output it, make sure that numEntered != 0, or it will crash.

For the loop, have it loop while the newest entered number is not negative.
Topic archived. No new replies allowed.