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
I'd start with this:
Shouldn't you be returning:
Besides this, you should find a way to set
sum
to zero between initial calls to the function, because otherwise it will accumulate the sum of all the arrays you attempt to sum up.The point is, you never initialize
sum
, so it has some sort of garbage there.Whose idea was it to use a recursion of all things when a simple
for
loop would do the trick? Is this homework?This is how I've done it:
You never actually add the values in
x[]
andy[]
tosum
and in addition,index
is always equal to0
. You should probably pass it as another parameter to the function:You don't actually need the
sum
variable.The problem is that you are using a static variable
sum
instead ofx[size - 1]
. Showing how to fix this is redundant at this moment (7 answers already do this). However, this can be done in one line with built in c++ capabilities:You're trying to craft something extremely overengineered. You need two things - an edge case (recursion cut-off) and a general case (descend in recursion). In your case the edge case is "array size is zero" and the general case is "grab the first element and pass the rest of array into recursion".
It could be something like this: