0
[SOLVED] Could someone explain how this function works? I've solved when I put the variable num as 5, but something is wrong.
int recursive(int num) { if (num == 1) return 2; return num * recursive(num-1); }
4 Respostas
+ 4
For num = 5.
recursive ( 5 ) will return
5 * recursive ( 5 - 1)
= 5 * ( 4 * recursive (4-1) )
= 5 * 4 * ( 3 * recursive (3-1))
= 5 * 4 * 3 * ( 2 * recursive (2-1))
= 5 * 4 * 3 * 2 * 2 { as recursive (1) will return 2 }
= 240
So the final value returned by recursive (5) should be 240.
+ 3
recursive(5)
num*recursive(4)
num*recursive(3)
num*recursive(2)
num*recursive(1).
recursive(1) returns 2
recursive(2) returns num*recursive(1) = num*2=2*2=4
recurisve(3) returns num*recursive(2) = num*4=3*4=12
recurisve(4) returns num*recursive(3) = num*12=4*12=48
revursive(5) returns num*recursive(4) =num*48=5*48=240
functions were pushed onto the stack and then popped off .
Refer to the following video if you want to see visualization for it .
https://youtu.be/AIwxbJ5mP8M
+ 1
Thanks for effort! Arsenic
0
Thanks for effort! Abhay