Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Find the Fibonacci Series without Using Recursion
When it is required to find the Fibonacci series without using recursion technique, we can use iterative methods with loops. The Fibonacci sequence starts with two initial numbers, and each subsequent number is the sum of the two preceding ones.
What is Fibonacci Series?
The Fibonacci series is a sequence where each number is the sum of the two preceding numbers. For example: 0, 1, 1, 2, 3, 5, 8, 13, 21...
Method 1: Using While Loop with User Input
This approach takes custom starting numbers and term count from the user ?
first_num = 2
second_num = 8
num_of_terms = 8
print("First two numbers:", first_num, second_num)
print("The numbers in fibonacci series are:")
count = 2 # Already printed first two numbers
while count < num_of_terms:
third_num = first_num + second_num
print(third_num)
first_num = second_num
second_num = third_num
count += 1
First two numbers: 2 8 The numbers in fibonacci series are: 10 18 28 46 74 120
Method 2: Traditional Fibonacci Series
The classic Fibonacci series starting with 0 and 1 ?
def fibonacci_series(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fib_list = [0, 1]
for i in range(2, n):
next_num = fib_list[i-1] + fib_list[i-2]
fib_list.append(next_num)
return fib_list
# Generate first 10 Fibonacci numbers
result = fibonacci_series(10)
print("First 10 Fibonacci numbers:", result)
First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Method 3: Simple For Loop Approach
A straightforward approach using a for loop ?
n = 8
a, b = 0, 1
print("Fibonacci series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Fibonacci series: 0 1 1 2 3 5 8 13
How It Works
The iterative approach uses three key steps:
- Initialize − Start with two numbers (typically 0 and 1)
- Calculate − Add the two numbers to get the next number
- Update − Shift the values: first = second, second = sum
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| While Loop | O(n) | O(1) | Custom starting values |
| Function with List | O(n) | O(n) | Storing all numbers |
| For Loop | O(n) | O(1) | Simple implementation |
Conclusion
Iterative methods are more efficient than recursion for Fibonacci series as they avoid repeated calculations. The while loop approach works well for custom starting values, while the for loop method is ideal for the traditional sequence.
