Recursive sum of an array in C
arrays, c, recursion, sum
Solution
You could add a third argument, which is the running total calculated so far (start it as `0`).
When you recursively call the function, pass the running total.
int arr_sum( int arr[], int n, int sum )
{ // must be recursive
if (n < 0) {
return sum;
}
sum += arr[n];
return arr_sum(arr, --n, sum);
}
Alternatively, you change it to not require passing the `sum` variable like so.
int arr_sum( int arr[], int n )
{ // must be recursive
if (n < 0) {
return sum;
}
return arr[n] + arr_sum(arr, n - 1);
}
In this way, it is similar to finding a number in the Fibonacci sequence.
Problem
Hello I'm learning recursion in C and I am trying to find the sum of the elements. This is my main: ``` int main() { int arr[] = {1,2,3,4,5}; int sum; sum = arr_sum(arr,4); printf("\nsum is:%d",sum); return 0; } ``` And my recursive function: ``` //n is the last index of the array int arr_sum( int arr[], int n ) { // must be recursive int sum = 0; //base case: if (n < 0) { return sum; } else{ sum = sum + arr[n]; } //make problem smaller arr_sum(arr,n-1); } ``` The output is: ``` sum is :0 ```