问题
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
回答1:
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.
回答2:
Try this for your recursive function:
int arr_sum( int arr[], int n ) {
if (n < 0) {
//base case:
return 0;
} else{
return arr[n] + arr_sum(arr, n-1);
}
}
you need to add your n-th case to your n-1 case until you get to the base case.
回答3:
Try this modified version of your program and work out on pen/paper the way it flows through. Hope it helps.
#include <stdio.h>
//n is the last index of the array
int
arr_sum(int arr[], int n )
{
//base case:
if (n == 0) {
return arr[0];
}
return (arr[n] + arr_sum(arr,n-1));
}
int
main(void)
{
int arr[] = {1,2,3,4,5};
int sum;
sum = arr_sum(arr,4);
printf("\nsum is:%d\n",sum);
return 0;
}
回答4:
You are not returning any thing from else part.You also have return from that. like.
return arr_sum(arr,n-1)+arr[n];
so this call the function again and again until n will be zero.
you got my point?
回答5:
The problem with your code is that everytime when your recursive function calls, it initializes the sum as 0
.
Declare sum
outside the recursive method that will solve the problem.
来源:https://stackoverflow.com/questions/15801957/recursive-sum-of-an-array-in-c