When using a recursive function, an implicit stack is supported that keeps track of the values returned from each recursive call.
Now consider your example for a given value n = 5
>Processing fib(5)... Call fib(3) and fib(4). >Processing fib(3)... Call fib(1) and fib(2). >Processing fib(1)... Return 1! >Processing fib(2)... Return 1! >Processing fib(4)... Call fib(2) and fib(3). >Processing fib(2)... Return 1! >Processing fib(3)... Call fib(1) and fib(2). >Processing fib(1)... Return 1! >Processing fib(2)... Return 1! >5 is the 5th Fibonacci number
Analysis . The program requests a search number on line 15 and assigns a target number to this number. Then it calls fib () with the target. Running branches to the fib () function, where on line 28 it prints its argument.
The argument n is checked to ensure that it is 1 or 2 on line 30; if so, returns fib (). Otherwise, it returns the sum of the values returned by calling fib () on n-2 and n-1.
In the example, n is 5, so fib (5) is called from main (). Execution proceeds to the function fib (), and n is checked for a value less than 3 on line 30. The test fails, so fib (5) returns the sum of the values returned by fib (3) and fib (4). That is, fib () is called on n-2 (5 - 2 = 3) and n-1 (5 - 1 = 4). fib (4) will return 3, and fib (3) will return 2, so the final answer will be 5.
Since fib (4) passes into an argument that is at least 3, fib () will be called again, this time from 3 and 2. fib (3) will in turn call fib (2) and fib (1). Finally, calls to fib (2) and fib (1) will return 1 because these are stopping conditions.
source share