# Thread: Average value of recursive function

1. ## Average value of recursive function

This function returns the sum of "n" different values. (The running time of an algorithm) But I want the function to return the average value of all those values instead of the sum. Anyone got any ideas? Code:
```double sum(double alg, int n)
{

if (n == 1) {
return alg;

}

return (alg + sum(alg,n-1));
}``` 2. Nope... this function returns 'n*alg', the average is 'alg'.

And... if n <= 0 (n is a signed integer!) it will return 'alg*((2³¹ - abs(n)) + 2³¹-2)'. 3. Originally Posted by flp1969 Nope... this function returns 'n*alg', the average is 'alg'.

And... if n <= 0 (n is a signed integer!) it will return 'alg*((2³¹ - abs(n)) + 2³¹-2)'.
Nah it returns the sum. And "alg" is the function of the algorithm that also returns the "clock-time" of that specific algorithm. "n" are the number of times the function is asked to run.  4. If I understand what you're getting at, maybe something like this.
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

double func() {
return (double)rand() / RAND_MAX * 3 + 10; // 10.0 to 13.0
}

double avg(double (*f)(), int n, double s, int i) {
return i == n ? s / n : avg(f, n, s + f(), i + 1);
}

double sum(double (*f)(), int n) {
return n == 0 ? 0 : f() + sum(f, n - 1);
}

int main() {
srand(time(0));
printf("%f\n", sum(func, 5));
printf("%f\n", avg(func, 5, 0, 0));
}``` Popular pages Recent additions alg, average, function, return, values 