is my first time here so i dont know exactly how it works, so sorry for the mistakes.
What's the result from this function, when we give as "aktueller Parameter" the number 3?
(The original text:
Welches Ergebnis liefert diese Methode, wenn bei einem Aufruf als aktueller Parameter der Wert 3 übergeben wird?
Im studying in German, so i dont really know the english terms :/ )
public int m(int p)
{
int result;
if (p == 0)
{
result = 0;
}
else
{
result = 3*p + m(p-1);
}
return result;
}
I have already tried it and the answer is 18, but when im trying to do it without any program the answer i find is 15:
result = 3 * 3 + 3(3-1);
Can someone please explain me why is 18 and not 15? Im assuming that i am making something wrong.
Thank you in advance.
Let's break down this recursive call:
With m(3), p isn't 0, so we return 3*3 + m(2);.
3*3 + (m(2))
With m(2), p isn't 0, so we return 3*2 + m(1);.
3*3 + (3*2 + m(1))
With m(1), p isn't 0, so we return 3*1 + m(0);.
3*3 + (3*2 + (3*1 + m(0))
With m(0), p is 0, so we return 0. Then the recursive call stack unwinds.
3*3 + (3*2 + (3*1 + (0)) =
9 + (6 + (3 + 0)) =
9 + (6 + 3) =
9 + 9 =
18
When you see m(p-1), that means that you're calling the function m again from inside itself, which is called recursion.
Essentially, the arithmetic it's doing is 3*3+3*2+3*1 = 18.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With