Python Program to generate Fibonacci Series using Recursion

In this tutorial, we will discuss a Python program to generate Fibonacci Series using Recursion.

Before going to the program first, let us understand what is Fibonacci Series.

Fibonacci Series:

  • The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

Related: Python Program for the sum of Natural Numbers using Recursion

Program code to generate Fibonacci Series using recursion in Python

# Fibonacci Series Using Recursion in Python
def fibonacci(n):
    if n <= 0:
        return "Input should be a positive integer."
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

terms = int(input("Enter the number of terms: "))
if terms < 1:
    print("Please enter a positive integer.")
else:
    print(f"The first {terms} terms of the Fibonacci series are:")
for i in range(1, terms + 1):
    print(fibonacci(i), end=" ")

Explanation

  1. Function Definition: The fibonacci function takes an integer n as input and returns the nn-th term in the Fibonacci series using recursion.
  2. Main Program: The program prompts the user to enter the number of terms and then generates the Fibonacci series up to that number using the fibonacci function and prints the result.

Output

Python Program to generate Fibonacci Series using Recursion

  • When you run the above program, it will prompt you to enter the number of terms.
  • After entering the number, it will generate the Fibonacci series up to that number of terms using recursion and print the result.

Conclusion

  • In this tutorial, we learned how to generate the Fibonacci series using a recursive approach in a Python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *