i am a bit confused in using array in doing recursion, can anyone correct my mistake?
new update, based on question required some of the line cannot be edit
double sum_of_array(double x[],int size)
{
static double sum; <---can be edit
int index = 0; <--can be edit
if(index<size){
return sum + sum_of_array(x,size-1); <--can be edit
}
else {
something ; <--can be edit
return sum; <--can be edit
}
}
int main(void){
double x[] = {4.5,5.0,6.8};
double y[] = {4.7,3.4,2.5,5.2};
cout<<"Sum X = "<<sum_of_array(x,3)<<endl;
cout<<"Sum Y = "<<sum_of_array(y,4)<<endl;
return 0;
}
output:
Sum of the element in X[]=15.3
Sum of the element in Y[]= 15.8
The logic of your recursive function is just wrong. You never actually read the contents of the array. I'm surprised you got any meaningful output out of that.
You need to rethink of the recursive definition to perform this addition.
Base case(s):
Sum of an empty array is
0.
.i.e.,
sum_of_array(x, 0) == 0.
Sum of a 1-element array is the value of the element.
i.e.,
sum_of_array(x, 1) == x[0]
Recursive case:
Sum of an n-element array is the sum of the nth element and the sum of the first
n-1
elements.i.e.,
sum_of_array(x, n) == x[n-1] + sum_of_array(x, n-1)
Figure out how to encode this logic in your function.
Ok last attempt:
then
I hope I can still chime in with my answer. The most recent answer excluding mine is from 2011.
This is yet another solution to calculate the sum of all elements in an array.
Analysis of this algorithm would yeild a run-time of
O(n*log(n))
. However, you'd do wise to take this statement with a pinch of salt.Error is you did not initialized static variable sum.
There are quite some errors in this code:
Ok then it should be like this:
then call
IE you always call the first time with 0 as the index