This Python program reads a positive integer n and generates the first n terms of the Fibonacci sequence using a recursive function.
It demonstrates how recursion can be used to compute each term based on the two preceding ones.
def fibonacci_recursive(k):
if k == 0:
return 0
elif k == 1:
return 1
else:
return fibonacci_recursive(k - 1) + fibonacci_recursive(k - 2)
n = int(input("Enter the number of Fibonacci terms: "))
print(f"The first {n} Fibonacci terms:")
for i in range(n):
print(fibonacci_recursive(i))
Enter the number of Fibonacci terms: 6
The first 6 Fibonacci terms:
0
1
1
2
3
5
Here’s how the program works:
- The fibonacci_recursive() function defines the base cases for 0 and 1
- For all other values, it recursively adds the two previous terms
- The loop prints each term from 0 to n - 1