Search code examples
crecursionaccumulator

Function that counts arbitrary function 1 to 10 in C


How do I write a function that have a input function (is objective to any function), array of input numbers and length of input array?

Function:

double accumulator(double (*function)(double, double), double array[], int length)

Main:

int main(){
   double array[10];

   for (int i=0; i<10; i++)
      array[i] = i+1;

   printf("Sum is: %g\n", accumulator(sum,array,10));
   printf("Product is: %g\n", accumulator(product,array,10));

   return 0;
}

For example sum should be 55 (1 + 2 + .... + 10) and product 362880 (1 * 2 * ... * 10). I guess the function should by recursive but I still cant get the right results :/

I have got this non-recursive solution but it of course works only for sum...

double accumulator(double (*function)(double, double), double array[], int length)
{
    int temp = 0;
    for (int i = 0;i<length;i++)
    {
        temp = (*function)(temp, array[i]);

    }
    return temp;
}

on the top of course:

double sum(double x, double y){
    return x+y;
}
double product(double x, double y){
    return x*y;
}

Solution

  • It doesn't work for multiplication because multiplying anything by 0 gives, well 0

    you need to use first element as an initial value

    double accumulator(double (*function)(double, double), double array[], int length)
    {
        int temp = array[0]; 
        for (int i = 1; i < length;i++) // start from #1
        {
            temp = (*function)(temp, array[i]);
    
        }
        return temp;
    }