Recursive average
I want to calculate the average using a recursive function and when I get to the end of input the average is already calculated.
What I mean is not using the algorithm of multiplying what the function returns with the size-1 ad the number and divide all by size: not like this (Func(parameters)*(size-1)+num)/size |
That would be a very expensive way of calculating an average:
Code:
|
Quote:
So what you're sayin jschiwal is that the function should call itself at least twice. I can't do that because I'm also getting the input ( the numbers one by one). Do you have an example of C code? Thanks |
that must mean the function gets input too?
not typically classic recursion. homework? |
Essentially the question is why recursive?
I think you need to provide a little more for everyone to go on. Sure it can be done, but why do you want to do it that way? |
Quote:
|
Okay, but one more question, why don't you want to use an array?
|
because I'm not alowed.
|
some sort of pseudo code..
Code:
average(num,avg,&count) { |
Quote:
|
Quote:
Quote:
|
Recursion would be called with an array, and would break up the array into two parts and call itself again until it has two adjacent elements and then would unwind, taking the results (total and number of elements) of two calls, until the main routine has the total and the number of elements. So using recursion wouldn't make sense for this problem.
Also, asking for c code for homework problems (the answer) is a no-no on this site. The problem you want to solve is how to keep a running average of numbers given one number at a time. So this is really a basic math problem and a test of your knowledge of different variable types in C. |
Average and count should start as 0. That's the basic algorithm for solving an average number entered by number entered. If it's a homework question though, you should say so. People will help you out here, but probably not give you actual code. This is more for your own benefit, than not wanting to do someone else's homework.
|
As already stated we are happy to help with homework, but few people will actually give you code, because in the long run it doesn't help. So please be honest and also try and explain what you have managed so far.
Your recursive function needs to do a couple of things.
From that have a go at coding it. Show us what you manage to achieve and we can give you more advice if necessary. |
Quote:
now the last question. I know that average and counter should be initialized at 0, that's why I asked, but if this is done inside the function it would be initialized at every recursion. if the function is called (inside the program) with average and counter at 0, than it's not a very effective function. thank you all for your input. |
All times are GMT -5. The time now is 04:01 PM. |