I guess the expected solution looks somewhat like this:
int sumBeforeX(const int *a, int x)
{
if (x == *a) return 0; // termination condition
return *a + sumBeforeX(a+1, x); // recursive step
}
To understand that, note that arrays can't be passed in C, therefore their type in a function parameter is adjusted to the corresponding pointer type, and a pointer to the first element is passed instead. I made this explicit in the snippet above, directly writing the pointer type.
The const
is just a little improvement: the function never modifies your array through this pointer, so make this explicit as well.
Also note how this implementation never assigns anything. This is a typical property of functional programming, and recursion is especially used with functional programming. The function call is free of side effects.
Side note: don't write this recursively in real-world C code, if you're lucky, the compiler optimizes the recursion away (in this simple case, a good compiler should do it), but that shouldn't be relied upon, and if the recursion stays, performance will typically suffer and you might get the risk of stack overflows if your recursion gets really deep. Therefore, just for completeness, the real-world code should look more like this:
int sumBeforeX(const int *a, int x)
{
int sum = 0; // accumulator to replace recursion
while (*a != x) sum += *a++;
return sum;
}