Apply recursive call to Print Fibonacci series up to term n

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

n = int(input('Enter number of terms: '))
print('Fibonacci sequence:')
for i in range(n):
    print(fab(i))
Output:
Enter number of terms: 5
n = 5
Fibonacci sequence:
0
1
1
2
3

Certainly! The provided Python code defines a function fab (which should be named fib for Fibonacci) that recursively calculates the Fibonacci sequence. The code also prompts the user to input the number of terms they want in the sequence and prints the sequence. Here’s a detailed explanation of how the code works:

Explanation

  1. Function Definition (def fab(n):):
  • This line defines a function named fab that takes one parameter, n, which represents the position in the Fibonacci sequence.
  1. Base Case for Recursion (if(n <= 1):):
  • If n is less than or equal to 1, the function returns n. This is because the first two terms of the Fibonacci sequence are 0 and 1.
  1. Recursive Case (else:):
  • If n is greater than 1, the function returns the sum of the previous two Fibonacci numbers (return(fab(n - 1) + fab(n - 2))). This is the essence of the Fibonacci sequence where each number is the sum of the two preceding ones.
  1. Input and Output:
  • The user is prompted to input the number of terms in the Fibonacci sequence:
    python n = int(input('Enter number of terms:'))
  • The program then prints “Fibonacci sequence:” as a header for the output.
  • A for loop iterates from 0 to n - 1, calling the fab function for each term and printing the result:
    python for i in range(n): print(fab(i))

Example

Let’s go through an example where the user inputs a number of terms. Suppose the user inputs the following:

Enter number of terms: 5

The code execution will be as follows:

  • Input Number of Terms:
  n = 5
  • Fibonacci Sequence Calculation:
  • fab(0) returns 0
  • fab(1) returns 1
  • fab(2) calls fab(1) and fab(0), returns 1 + 0 = 1
  • fab(3) calls fab(2) and fab(1), returns 1 + 1 = 2
  • fab(4) calls fab(3) and fab(2), returns 2 + 1 = 3
  • Output:
  Fibonacci sequence:
  0
  1
  1
  2
  3

Summary

This code defines a recursive function fab to calculate the Fibonacci sequence. It prompts the user for the number of terms they want and then prints the first n terms of the Fibonacci sequence. The function fab uses a straightforward recursive approach to calculate each term, where each number in the sequence is the sum of the two preceding ones.

Leave a Reply

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