It can be hard to explain. But of course the fundamental principle of recursion is that the function may call itself. In this case the number of calls can become very large.
Here's an example for fib(5) which happens to give the result 5, though the actual number is quite tricky to understand, because of the number of calls involved. At first,
fib(5)
is calculated as the sum of
fib(4) + fib(3)
. Well, it can't actually do the addition immediately, as each of the two expressions must itself be evaluated first. Hence fib(4) is evaluated as the sum of
fib(3) + fib(2)
and so on.
1 2 3 4 5 6 7 8 9 10 11
|
Fib(5)
Fib(4) + Fib(3)
Fib(3) + Fib(2) + Fib(2) + Fib(1)
Fib(2) + Fib(1) + Fib(1)+Fib(0) + Fib(1)+Fib(0) + 1
Fib(1)+Fib(0) + 1 + 1 + 0 + 1 + 0 + 1
1 + 0 + 1 + 1 + 0 + 1 + 0 + 1
|
As you can see, the final result is the sum of a lot of 1 and 0 values, which adds up to 5.
I was going to illustrate
fib(6)
which follows the same principles, giving 8 as the result, but it was growing too wide to fit on the screen comfortably.