Python Program To Print Fibonacci Series Using Recursion

Python Program To Print Fibonacci Series Using Recursion

In this tutorial, you will learn to write a Python Program To Print Fibonacci Series Using Recursion.

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers.

The first two numbers in the series are 0 and 1, and the rest of the series is generated by adding the previous two numbers.

Therefore, the series starts like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, …

To understand this program you should have an understanding of the following topics:

  1. Python Recursion
  2. For Loop

Python Program To Print Fibonacci Series Using Recursion

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# get the number of terms from the user
n = int(input("Enter the number of terms: "))

# print the first n terms of the series
for i in range(n):
    print(fibonacci(i), end='  ')

Output

Enter the number of terms: 13
0 1 1 2 3 5 8 13 21 34 55 89 144

In this code, we define a recursive function called fibonacci().

This function takes an integer n as input and returns the nth term of the Fibonacci series.

If n is 0 or 1, we simply return n.

Otherwise, we calculate the nth term by recursively calling the fibonacci function with arguments n-1 and n-2, and adding the results.

We then get the value of n from the user.

This value determines how many terms of the Fibonacci series we want to print.

We use a for loop to iterate over the first n terms of the series.

And we print the value of the ith term by calling the fibonacci function with argument i.

Note that this method is less efficient than the other methods we’ve discussed, especially for large values of n.

This is because it involves a lot of redundant computation due to the recursive calls.

However, it’s a useful example of how recursion can be used to solve problems that involve self-similarity.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x