Four clear steps — then pick a fixed term count or a value ceiling.
State the seeds: a = 0, b = 1.
Print (or store) the current term a.
Advance with a, b = b, a + b.
Stop after n terms, or while a <= max_val.
Method
Idea
Time
Best for
First n terms
Loop n times with two-variable shift
O(n)
Interviews, classic prompt
Until max value
While a <= max_val, same shift
O(k)
List all terms within a limit
Pseudocode
Pseudocode
function PrintFirstN(n):
if n <= 0:
return empty
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = next
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Seeds
a, b = 0, 1
Advance
a, b = b, a + b
n terms
for _ in range(n): ...
Until max
while a <= max_val: ...
First ten
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Avoid
Naive recursion to print many terms
Format
", ".join(parts) — no trailing comma
Try it
Live Preview
Enter how many terms to print. Exact values via BigInt in the browser.
Whole numbers from 0 to 100 in this preview. Tap a chip or type a value.
Result
n = 10
First 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Trace
Worked Walkthrough — First 6 Terms
Start at (0, 1), print a, then shift with a, b = b, a + b.
Calculation
Start: a = 0, b = 1
Step 1: print 0 → a, b = 1, 0+1 = (1, 1)
Step 2: print 1 → a, b = 1, 1+1 = (1, 2)
Step 3: print 1 → a, b = 2, 1+2 = (2, 3)
Step 4: print 2 → a, b = 3, 2+3 = (3, 5)
Step 5: print 3 → a, b = 5, 3+5 = (5, 8)
Step 6: print 5 → a, b = 8, 5+8 = (8, 13)
Printed: 0, 1, 1, 2, 3, 5
Code
Python Programs
Start with a fixed term count for interviews. Switch the stop rule when you need every term up to a maximum value.
Example 1 — First n Terms
Two rolling variables stream the series. Collect strings, then join for clean commas.
python
def display_fibonacci(n: int) -> None:
if n <= 0:
print("Need a positive term count.")
return
a, b = 0, 1
parts = []
for _ in range(n):
parts.append(str(a))
a, b = b, a + b
print(f"First {n} terms: " + ", ".join(parts))
display_fibonacci(10)
Output
First 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
How It Works
Reject n <= 0 so the empty case is explicit.
Seed a, b = 0, 1 — the usual interview convention.
Each loop: append a, then set a, b = b, a + b.
Repeat exactly n times. For n = 10 you get 0 through 34.
", ".join(parts) formats the list without a trailing comma.
Example 2 — All Terms ≤ max_val
Same update rule; stop when the current term would exceed the limit.
python
def display_fibonacci_until(max_val: int) -> None:
if max_val < 0:
print("max_val must be nonnegative.")
return
a, b = 0, 1
parts = []
while a <= max_val:
parts.append(str(a))
a, b = b, a + b
print(f"Fibonacci <= {max_val}: " + ", ".join(parts))
display_fibonacci_until(100)