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
Best Answer
Try this for your recursive function:
you need to add your n-th case to your n-1 case until you get to the base case.