[Solved] Sum of an array recursively using one parameter in C


Not Possible

Two problems:

  1. Where does the array end?

In C, arrays are simply blocks of memory and do not have a length property. It is possible to read unpredictable numbers off the end of the array, from other portions of memory.

In the posted code, sizeof(*arr) apparently is being used to get the length of the array in the pointer arithmetic q = p + sizeof(*arr) - 1

But does sizeof determine array length? Let’s find out…

#include <stdio.h>
void main(){
  int a[10] = {0,1,2,3,4,5,6,7,8,9};
  int * p = a;
  int l = sizeof(*p);
  printf("%d\n",l);
}

This prints 4 when compiled and run with gcc, not 10.

Why 4? Because 4 is the size of an int.

And this demonstrates that sizeof will not provide array length.

Therefore, a function int sum(int *arr) will not know when to stop reading unless it is either given a sentinel value for termination or an explicit length of the sum. In strings, the terminal value is 0 but the problem with using 0 here is that it is a perfectly valid number to add in to a sum.

  1. Need for an accumulator.

Most recursive sum functions are essentially fold operations and as such need an accumulator to store the partial result.

Now the accumulator might be put in a static variable, but it isn’t generally done that way because it isn’t thread safe and leads to more complex code involving copying the final result and resetting the accumulator.

This suggests including an accumulator parameter to hold the sum.

If we also add a parameter for length, we could write:

int sum(int *arr, int len, int accumulator){ 
    if (len==0) return accumulator;
    else return sum(arr+1,len-1,accumulator+*arr);
}

Alternatively, you can use the function stack to store the accumulations and cut out the accumulator parameter like this:

int sum(int *arr, int len){ 
    if (len==0) return 0;
    else return sum(arr+1,len-1)+*arr
}

But a single parameter int sum(int *arr) is impossible as it lacks a parameter to terminate the summing procedure.

0

solved Sum of an array recursively using one parameter in C