Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding recursion in c++

I think I'm understanding the principle behind recursion, for example the stack like behaviour and the way the program "yo-yo's" back through the function calls, I seem to be having trouble figuring out why certain functions return the values that they do though, the code below returns 160, is this due to the return 5 playing a part, I think I'm right in saying it will go 4*2 + 8*2 + 12*2 etc.. I'm really doubting that when changing my values though.

Would anybody be able to offer a brief explanation as to which values are being multiplied?

cout << mysteryFunction(20);

int mysteryFunction (int n)
{
 if(n > 2)
  {
   return mysteryFunction(n - 4)*2;
  }

   else return 5;
}
like image 376
beardedranga Avatar asked Feb 21 '26 15:02

beardedranga


2 Answers

If you are interested in actual call stack:

mysteryFunction(20):
[n > 2] -> mysteryFunction(16) * 2
           [n > 2] -> mysteryFunction(12) * 2
                      [n > 2] -> mysteryFunction(8) * 2
                                 [n > 2] -> mysteryFunction(4) * 2
                                            [n > 2] -> mysteryFunction(0) * 2
                                                       [n <= 2] -> 5
                                            5 * 2 = 10
                                 10 * 2 = 20
                      20 * 2 = 40
           40 * 2 = 80
80 * 2 = 160

More generally: 20 = 4*5, so 5 * 2^5 = 5 * 32 = 160.

like image 198
Mateusz Grzejek Avatar answered Feb 24 '26 07:02

Mateusz Grzejek


mysteryFunction(20) => 80 * 2 = 160
mysteryFunction(16) => 40 * 2 = 80
mysteryFunction(12) => 20 * 2 = 40
mysteryFunction(8) => 10 * 2 = 20
mysteryFunction(4) => 5 * 2 = 10
mysteryFunction(0) => 5
like image 39
αƞjiβ Avatar answered Feb 24 '26 07:02

αƞjiβ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!