Recursion

closed account (G3AqfSEw)
Define a recursive function int sum_range(int low, int high) that computes the sum low+(low+1)+(low+2)+⋯+high using recursion. You can assume low≤high.

1
2
3
4
int sum_range(int low, int high) 
{
??
}
recursion calls itself, so you need the following form for your function.
Can you figure out what to put in the body though?


int sum_range(int low, int high)
{
if (stopping criteria)
return something; //implied else, due to returns

return ( low+ sum_range(something, something) )
}

its a lot like a loop. you are trying to get it to do

while (!condition)
value += function();

but it looks a little weird the first few times you do it.
closed account (G3AqfSEw)
int sum_range(int low, int high) {
if (low == high)
return 1;
else {
return (low + sum_range(?, ?));
}
}

I'm not sure what to put in the sum_range(something, something).
1
2
3
4
5
6
7
8
int sum_range( int low, int high )
{
   if( low > high ) return 0 ; // empty range, return 0
   
   else if( low == high ) return low ; // reached end of range
   
   else return low + sum_range( low+1, high ) ; 
}
I think its

if (low == high)
return low; //the +1 was handled in the call... which brings us...

(low + sum_range(low+1, high));

I could be wrong. I don't do well with series that have no practical application on hand, I don't do as well with the abstract stuff.

Topic archived. No new replies allowed.