Recursive Functions
Recursive Fibonacci
def fibonacci(n):
if ( n < 0 ): # Termination condition
print("Invalid input")
return
elif ( n==0 ): # Termination condition
return 0 # First Fibonacci number is 0
elif ( n==1 ): # Termination condition
return 1 # Second Fibonacci number is 1
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive Call
print(fibonacci(15))
The recursive flow of execution of the fibonacci (fib
for short) function for n = 4 is as follows:
fib(4) = fib(3)
| |-> fib(3) = fib(2)
| | |-> fib(2) = fib(1)
1. | | | |-> fib(1) = 1
3. | | (+)
| | |
| | fib(0)
2. | | |-> fib(0) = 0
5. | (+)
| |
| fib(1)
4. | |-> fib(1) = 1
|
9. (+)
|
fib(2)
|-> fib(2) = fib(1)
6. | |-> fib(1) = 1
8. (+)
|
fib(0)
7. |-> fib(0) = 0