Python program to print Fibonacci series using iteration
#Python Fibonacci series using recursion #python program #fibonacci series
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones. It starts with 0
and 1
, and every subsequent number is the sum of the previous two numbers. The Fibonacci sequence is commonly used in mathematical algorithms, dynamic programming, and problem-solving in computer science.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
Let's implement the Fibonacci series using a while loop for better performance and efficiency.
# Fibonacci Series using Iteration
a, b = 0, 1 # First two terms
n = int(input("Enter the number of terms in the sequence: "))
print(a, b, end=" ")
for _ in range(n - 2): # Loop to generate the remaining terms
c = a + b
a, b = b, c
print(c, end=" ")
0
and 1
.n
) to generate.n-2
times since the first two numbers are already printed.c = a + b
.a
and b
are updated for the next iteration.Enter the number of terms in the sequence: 10
0 1 1 2 3 5 8 13 21 34
🔹 Better Performance: Iteration is more efficient than recursion for larger values of n
, as recursion involves repeated calculations.
🔹 Less Memory Usage: Iterative solutions do not require extra function calls, making them memory-efficient.
🔹 Faster Execution: Iterative approaches run in O(n) time complexity, while naive recursion can take O(2^n) time.
If you want to use recursion, you can implement it like this:
def fibonacci_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
num = int(input("Enter number of terms: "))
print([fibonacci_recursive(i) for i in range(num)])
⚠️ Note: Recursion is not recommended for large values of n
due to excessive function calls, which slow down execution.
In this tutorial, we explored how to print the Fibonacci series using iteration in Python. We also compared iteration vs recursion and explained why iteration is the better choice for performance. For optimized performance in larger datasets, dynamic programming or memoization techniques can further improve efficiency.
🚀 Next Steps: Try modifying the program to store the Fibonacci series in a list or optimize it further using dynamic programming techniques!
The program then prints the generated Fibonacci series. Although straightforward, the recursive method can lose efficiency for bigger values of n because it involves repeated calculations. Memorization or dynamic programming techniques can be used to store interim findings and reduce the need for repeated computations. This Solution is provided by Shubham mishra This article is contributed by Developer Indian team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Also folllow our instagram , linkedIn , Facebook , twiter account for more