Question

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;
}
Was it helpful?

Solution 2

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;
}

OTHER TIPS

What is wrong with:

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

    }
    return temp;
}

Either a different function or you need to supply the neutral element for the operation (0 for sum, 1 for product).

Your solution is almost there if you set temp = array[0] and start your loop at i = 1 instead of i = 0.

Two thoughts:

  1. You should use double temp rather than int temp.

  2. You need to have a different starting value for addition versus multiplication. A sum should start at temp = 0, but a product should start at temp = 1. Otherwise the product will always be 0.

    You could add add another initial value parameter:

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

    Or you use the first array element as the starting value (but then you'll need to check for the special case where the array is empty):

    double temp = array[0]; 
    

For what it's worth, your "accumulator" function is alternatively known as "reduce" in other functional programming contexts. That may help if you want to Google the term.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top