# Python Program to Display Fibonacci Sequence Using Recursion

Last Updated : 19 Apr, 2024

We are given a task to write the Fibonacci sequence using recursion. we will take the range as input of integer and then print the Fibonacci Sequence. In this article, we will see the method of Python Program to Display Fibonacci Sequence Using Recursion.

Example:

Input: n = 9
Output: 0 1 1 2 3 5 8 13 21
Explanation: Here, we have n = 9, and we print the
Fibonacci Sequence by adding one element with its
subsequent element.

## What is the Fibonacci Sequence?

The Fibonacci sequence is like a mathematical melody, where each number dances to the rhythm of the two preceding ones. It usually begins its graceful dance with the numbers 0 and 1. This sequence is not just a mere mathematical curiosity; it’s like a versatile performer that appears on the stages of various mathematical and computer science domains. The Fibonacci sequence is defined by the recurrence relation:

[Tex]F(n) = F(n-1) + F(n-2)[/Tex]

[Tex]where ( 0 ) = 0 F(0)=0 and ( 1 ) = 1 F(1)=1.[/Tex]

## Python Program to Display Fibonacci Sequence Using Recursion

Below, are the implementation of Python Program to Display Fibonacci Sequence Using Recursion.

• The code defines a recursive function, fib, to generate Fibonacci series.
• It also contains a function print_fib to handle edge cases and initiate the Fibonacci series printing.
• The program checks for invalid inputs and prints appropriate messages.
• It initializes the series with 0 and 1 and calculates subsequent terms by summing the previous two.
• The driver code calls print_fib with the desired number of Fibonacci series terms, which is set to 9 in this case.

### Implementation

Python3 # Recursive function to print the Fibonacci series def fib(n, prev1, prev2): if n < 3: return fn = prev1 + prev2 prev2 = prev1 prev1 = fn print(fn, end=" ") fib(n - 1, prev1, prev2) def print_fib(n): # When the number of terms is less than 1 if n < 1: print("Invalid number of terms") elif n == 1: print(0) elif n == 2: print("0 1") else: print("0 1", end=" ") fib(n, 1, 0) # Driver code if __name__ == "__main__": n = 9 # Function call print_fib(n) 

Output

0 1 1 2 3 5 8 13 21

Time complexity: O(n),
Auxiliary Space: O(n),

Previous
Next