HomeUncategorizedGenerate a Fibonacci series using a loop in Python

Generate a Fibonacci series using a loop in Python

🔢 What is the Fibonacci Series?

The Fibonacci series is a sequence of numbers where:

F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2)

So the series is:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

✅ Python Code Using Loop

# Number of terms
n = 10

# First two terms
a = 0
b = 1

# Print Fibonacci sequence
print("Fibonacci series up to", n, "terms:")

for i in range(n):
    print(a, end=' ')
    # Next number = sum of previous two
    c = a + b
    a = b
    b = c

🧠 Explanation (Step-by-step)

🔁 Loop-based logic:

  1. Start with a = 0, b = 1 (first 2 terms).
  2. Loop n times.
  3. In each iteration:
    • Print current value a.
    • Calculate next term c = a + b.
    • Shift values: a = b, b = c to prepare for next iteration.

🧮 Dry Run Example (n = 5):

Iterationabc = a + bPrinted
10110
21121
31231
42352
53583

📚 DSA Concept Behind Fibonacci Series

ConceptExplanation
Data Structure UsedVariables (a, b, c) — constant space.
Time ComplexityO(n) — because we loop n times.
Space ComplexityO(1) — no extra space is used except 3 variables.
Optimization TipUsing loop is better than recursion (which uses O(2^n) time and stack space).

🚀 Bonus: Store Fibonacci Series in a List

def fibonacci_list(n):
    fib = []
    a, b = 0, 1
    for _ in range(n):
        fib.append(a)
        a, b = b, a + b
    return fib

print(fibonacci_list(10))

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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