Delving more deeply into recursion
The primary characteristics of a recursive function have previously been covered. Almost all the problems that can be solved with an iterative solution can also be solved with a recursive solution. Let us take a look at the simple recursive solution of one of the most famous problems: the calculation of the nth Fibonacci number:
int fibonacci(int n){ Â Â Â Â if (n <= 1) return n; Â Â Â Â return fibonacci(n-1) + fibonacci(n - 2); }
Let us illustrate the process that happens when the preceding function is called. In our example, we will consider that the argument passed to the function is 6, which means that n
is equal to 6. The process starts like this:
Figure 8.5 – First call of the recursive fibonacci() function
The function calls itself until n
is equal to or smaller than 1, but what happens when it becomes equal to 1?
Figure 8.6 – When...