# Thread: compute arithmetic mean without knowing the number of items

1. ## compute arithmetic mean without knowing the number of items

Hello.

I am working on a program that will compute arithmetic mean of certain number of real numbers (in C double) without knowing the number of items.

I can think of two solutions.

1) I can declare an array of doubles of huge length and then ask user to start entering its values. After writing the first and every next term then before continuing I can ask the user whether they want to continue adding new values, or it is the end already. That would work.

2) Is there a way how to enter all values at the same time separated by space? Let's say that the user input could be:
Code:
`2 5 8 10`
or
Code:
`10 15 20.4 80 100`
or
Code:
`1 2 3`
Maybe in the 2) solution I can consider the user's input as a string and work out from that the numbers to compute their mean.
Is there a better way how to code the 2nd solution? 2. You might be able to read the values one by one, adding them to a running total, then in the end, divide by the number of values. This way, you do not need an array. 3. @laselight : reading one by one requires to know when do you stop. That requires to know number of items, which is not given. And asking when to stop after every entry is the 1) solution.

Or a special value, let's say a negative one e.g. -2.00001, can be entered to signify that this is the end of entering. 4. Originally Posted by nerio
reading one by one requires to know when do you stop. That requires to know number of items, which is not given.
Then you simply stop when there are no more items to read, i.e., when the next read results in a read error due to end of file.

If this is interactive input, then you could either require the user to trigger EOF, or designate a special value as the sentinel, e.g., a non-positive value. 5. Thank you for replies. The entering of negative value I have already mentioned in post #3. Thank you for helping me to get to these thoughts.

Original problem is solved now.

I am also interested in knowing how to solve it using the 2). Is there a smart way how to proceed from the numbers input that user inputs at the same time? I am sure I saw it somewhere how to do it in C. I think it was without strings. 6. Originally Posted by nerio
I am also interested in knowing how to solve it using the 2). Is there a smart way how to proceed from the numbers input that user inputs at the same time?
Once you have the input in a string, you can parse the string with sscanf or strtod in a loop. Popular pages Recent additions 