Fibonacci Series is a sequence of numbers in which each is the sum of the two preceding numbers. In simple terms, it is a series of numbers in which the next number is found by adding the two previous numbers. This tutorial will discuss writing a Python program to print the Fibonacci series using recursion.
What is Recursion?
Recursion is a process in which a function calls itself a subroutine. It is used in programming to solve problems that can be broken down into smaller, simpler problems. In the case of the Fibonacci series, we can use recursion to find the next number in the series by calling the function repeatedly until we reach the desired number.
How to Write a Python Program to Print Fibonacci Series using Recursion?
To write a Python program to print the Fibonacci series using recursion, we need to create a function that takes the number n as input and returns the nth number in the Fibonacci series. Here is the code:
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) # take input from the user terms = int(input("How many terms? ")) # check if the number of terms is valid if terms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(terms): print(fibonacci(i))
In this code, we first define a function called Fibonacci that takes the number n as input. If the value of n is less than or equal to 1, we simply return n. Otherwise, we call the Fibonacci function recursively with the values n-1 and n-2 and add them together to get the next number in the series. We then use a for loop to print the first n numbers in the series.
In this tutorial, we discussed writing a Python program to print the Fibonacci series using recursion. Recursion is a powerful tool in programming that can help us solve complex problems by breaking them down into smaller, more straightforward problems. The Fibonacci series is a great example of how recursion can be used to find the solution to a problem.