Definition
0, 1 seeds
Fk = Fk-1 + Fk-2.
Fibonacci starts with 0 and 1; each next term is the sum of the previous two. This tutorial covers n-term printing, a value-ceiling variant, memoized recursion, a live preview, worked Java examples, edge cases, and complexity.
0, 1 seeds
Fk = Fk-1 + Fk-2.
(a, b) shift
Print a, then a, b = b, a + b.
n or ≤ M
Fixed term count or value ceiling.
O(φn)
Memoize or iterate for real work.
BigInt
Exact terms in the browser up to 500.
Iterative
Linear updates with O(1) extra space.
The Fibonacci series starts with seeds 0 and 1. Every next value is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, …
It is a classic state-update pattern: keep two previous terms, print one, then move forward. Some books start with 1, 1 — the recurrence is the same; only indexing shifts.
It teaches loops, rolling state, and why naive recursion fails — skills that transfer to DP and sequence problems.
State the convention before coding.
(a, b) ← (b, a+b) streams the series.
Best default for printing many terms.
Values grow exponentially with k.
In short: print a starting at 0, then repeatedly replace (a, b) with (b, a + b).
Print the first n Fibonacci terms, or all terms up to a maximum value.
// seeds: 0, 1
// first 10: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
# <= 100: ... ends at 89 (next is 144) | Item | Type | Description |
|---|---|---|
n | int | Number of terms (positive for a non-empty series). |
maxVal | int | Optional ceiling: print while term ≤ maxVal. |
| Output | text | Space- or comma-separated Fibonacci numbers. |
function print_first_n_fibonacci_terms(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = next | Method | Idea | Notes |
|---|---|---|
| Iterative series | Two-variable shift | Best for printing many terms |
| Until max | While a ≤ M | Different stop rule, same update |
| Memoized recursive | Map memo on fib(k) | Good for single nth term |
| Goal | Pattern |
|---|---|
| Initialize | long a = 0, b = 1; |
| Advance | long next = a + b; a = b; b = next; |
| n terms | for (int i = 0; i < n; i++) |
| Until max | while (a <= maxVal) |
| First ten | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 |
| Format cleanly | StringBuilder append with separators |
Same recurrence — very different costs for series output.
a, b = b, a+bO(n) time, O(1) extra space
fib(n-1)+fib(n-2)Exponential recomputation
@Map memoO(n) for nth term with cache
iterate to printMention memo/matrix as follow-ups
Reach for Fibonacci when rolling state or sequence drills appear.
Classic loop and recursion-vs-iteration discussion.
Natural next step from product loops to recurrence.
Shows why overlapping subproblems need memoization.
Golden-ratio asymptotics make exponential growth concrete.
Print with a loop; reserve recursion for nth-term demos.
Key benefit: one short loop that teaches rolling state, stop conditions, and recursion tradeoffs.
Print the first n terms using exact BigInt arithmetic.
Three complete Java programs — first n terms, until a max value, and memoized recursive nth term. Click View Output to reveal sample console results.
Interview-style first-n-terms printer.
n = 10)Clean comma formatting with a two-variable update.
public class Main {
static void displayFibonacciTerms(int n) {
if (n <= 0) {
System.out.println("Need a positive term count.");
return;
}
long first = 0;
long second = 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i > 0) sb.append(", ");
sb.append(first);
long next = first + second;
first = second;
second = next;
}
System.out.println("Fibonacci series up to " + n + " terms: " + sb);
}
public static void main(String[] args) {
displayFibonacciTerms(10);
}
} Two rolling values stream the series. Building with StringBuilder avoids trailing-comma bugs.
Same recurrence with a different stop rule.
Continue while the current term stays within the limit.
public class Main {
static void displayFibonacciUntil(int maxVal) {
if (maxVal < 0) {
System.out.println("maxVal must be nonnegative.");
return;
}
long a = 0;
long b = 1;
StringBuilder sb = new StringBuilder();
while (a <= maxVal) {
if (sb.length() > 0) sb.append(" ");
sb.append(a);
long next = a + b;
a = b;
b = next;
}
System.out.println("Fibonacci numbers <= " + maxVal + ": " + sb);
}
public static void main(String[] args) {
displayFibonacciUntil(100);
}
} The first Fibonacci number greater than 100 is 144, so the printed list ends at 89.
Get the nth term without exponential recomputation.
fib(k)Use a memo array when you need a single term, not a full print loop.
import java.util.HashMap;
import java.util.Map;
public class Main {
static long fib(int k, Map<Integer, Long> memo) {
if (k < 0) {
throw new IllegalArgumentException("k must be nonnegative.");
}
if (k <= 1) {
return k;
}
if (memo.containsKey(k)) {
return memo.get(k);
}
long value = fib(k - 1, memo) + fib(k - 2, memo);
memo.put(k, value);
return value;
}
public static void main(String[] args) {
Map<Integer, Long> memo = new HashMap<>();
// 0-based: fib(0)=0, fib(1)=1, ..., fib(9)=34
for (int k = 0; k < 10; k++) {
System.out.println("F(" + k + ") = " + fib(k, memo));
}
}
} Without a cache, each call branches into two — exponential work. With a Map memo, each k is computed once (O(n) for F(n)). For printing a long series, prefer the iterative loop from Example 1.
Set a = 0, b = 1.
Output a as the next term.
Set a, b = b, a + b and repeat.
Stop after n terms or when a > max.
Trace the two-variable update starting from (0, 1).
| Step | (a, b) before | (a, b) after | |
|---|---|---|---|
| 1 | (0, 1) | 0 | (1, 1) |
| 2 | (1, 1) | 1 | (1, 2) |
| 3 | (1, 2) | 1 | (2, 3) |
| 4 | (2, 3) | 2 | (3, 5) |
| 5 | (3, 5) | 3 | (5, 8) |
| 6 | (5, 8) | 5 | (8, 13) |
Printed so far: 0, 1, 1, 2, 3, 5.
Where Fibonacci shows up beyond the interview prompt.
Rolling state and stop-condition practice.
Example: print first n terms.
Shows overlapping subproblems clearly.
Example: naive vs memoized fib.
Next classic sequence after product loops.
Example: this walkthrough chain.
List all terms up to a budget M.
Example: Fibonacci ≤ 100.
Golden ratio and exponential growth demos.
Example: Fk+1/Fk → φ.
Matrix exponentiation / fast doubling for huge n.
Example: O(log n) single term.
Pro Tip: say “seeds 0 and 1” before coding — indexing debates vanish.
Why this pattern works well in interviews and classwork.
Only two integers stream the entire series.
Same update for n terms or ≤ M.
First ten terms are easy to verify by eye.
Memoization, matrix pow, and φ asymptotics.
Pro Tip: lead with the iterative printer; offer memoized recursion only if asked for the nth term.
Small habits that keep Fibonacci solutions interview-ready.
Say 0, 1 (or 1, 1) before writing code.
Two variables beat naive recursion for printing.
Avoid trailing commas and messy separators.
Empty series or a clear message — pick one.
0…34 catches off-by-one shift bugs fast.
Pro Tip: Java long overflows after enough terms — mention BigInteger for huge indices.
Mistakes that commonly break Fibonacci solutions.
Calling fib(n) recursively to print many terms.
→ Use the two-variable iterative loop.
Mixing 0,1 with 1,1 without saying so.
→ State seeds explicitly in the answer.
Looping n-1 times or starting from 1 only.
→ Trace first 10 against 0…34.
Printing commas after every term including the last.
→ Collect then join.
Empty or bogus output when n ≤ 0.
→ Validate and message clearly.
Java long can overflow, so clarity and stop conditions still matter.
n ≤ 0Handle as empty/error depending on requirement.
Using join() avoids trailing comma issues.
Recomputes work exponentially; avoid for long series output.
State clearly whether the sequence starts with 0,1 or 1,1.
maxVal = 100Last printed term is 89; next would be 144.
Use BigInteger for huge indices — printing cost grows with digit count.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: keep two seeds, print the first, shift with a + b, and prefer iteration for series output.
| Task | Time | Extra space |
|---|---|---|
| First n terms (iterative) | O(n) | O(1) |
| All terms ≤ M | O(k) where k terms printed | O(1) |
| Naive fib(n) recursion | O(φn) | O(n) |
| Memoized fib(n) | O(n) | O(n) cache |
For interview printing tasks, the iterative approach is the right default. Extra space above ignores the output string/list size.
Fibonacci streams from seeds 0 and 1 by repeatedly replacing (a, b) with (b, a + b). Print with an iterative loop; use memoized recursion only when you need a single nth term.
Practice the three examples above, then continue to GCD for the classic Euclidean algorithm.
State seeds, avoid naive recursion for series printing, and verify against the first ten terms.
Stream the series the interview-friendly way.
0, 1
Definitiona, b = b, a+b
Coren or ≤ M
VariantsNaive recur
TrapO(n)
AnalysisThe ratio of consecutive terms Fk+1/Fk approaches the golden ratio φ = (1+√5)/2 as k grows.
Learn how to find the greatest common divisor with Euclidean division.
9 people found this page helpful