Recursive

i am a sucker at this....can anyone tell me where the 30 comes from in the output for this function.not where but why i dont get it...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int Test(int a, int b) 
{ 
cout<<a<<" "<<b<<endl; 
if (a==b) 
   return a; 
else if ( (a+2) == b) 
  return a + Test(a+1,b-2); 
else 
  return b + Test(a+1,b-2); 
} 

int main ( ) { 
cout<<Test(6,12); 
return 0; 
} 
Last edited on
Test(6, 12) =
12 + Test(7, 10) =
12 + 10 + Test(8, 8) =
12 + 10 + 8 =
30

By the way, there are inputs for which the function doesn't terminate. E.g. a + 1 == b.
tht was obvious, anyways it was a question in my test today and i couldnt figure it out...
thnx @helios
helios wrote:
By the way, there are inputs for which the function doesn't terminate. E.g. a + 1 == b.

Wow !
I could have never caught it with my naked eyes !!!
Registered users can post here. Sign in or register to post.