Hi
I just started reading about recursion so I'm not sure how things work. I can find general information about recursion but not as analytical as I would like it to be.
Say I have this code that computes Fibonacci numbers...
Say now that n = 5.
What exactly happens when line 6 is read? The method should return fib(4) + fib(3). Does it first compute fib(4) and only when it has a result computes fib(3)?
I understand than in order to compute fib(4) or fib(3) it has first to compute fib(2) and fib(1) which is the base case but I'm confused about the order in which this works.
Thanks a lot,
stack
I just started reading about recursion so I'm not sure how things work. I can find general information about recursion but not as analytical as I would like it to be.
Say I have this code that computes Fibonacci numbers...
Code:
public static long fib(int n){ if (n <= 1) return 1; else return fib(n-1) + fib(n-2); }
What exactly happens when line 6 is read? The method should return fib(4) + fib(3). Does it first compute fib(4) and only when it has a result computes fib(3)?
I understand than in order to compute fib(4) or fib(3) it has first to compute fib(2) and fib(1) which is the base case but I'm confused about the order in which this works.
Thanks a lot,
stack
Comment