- Rule
- sum of prior pair
Display Fibonacci Series in C
What you’ll learn
- The usual programming definition starting from
0and1, withFk = Fk-1 + Fk-2. - An
n-term printer matching the reference flow, with clean separators (no stray trailing comma). - A second pattern: print every Fibonacci number up to a ceiling, plus overflow notes and a live preview.
Overview
The Fibonacci sequence is the hello-world of stateful loops: two variables hold the previous pair, each iteration prints (or stores) one value and advances the pair forward.
Two programs
Ten terms (0 … 34) and values ≤ 100.
Live preview
First n terms with BigInt in the browser (no silent float rounding).
Rigor
Nonpositive term counts, int overflow horizons, and why naive recursion is avoided for series.
Prerequisites
for loops, printf, and integer addition.
#include <stdio.h>,int main(void), and functions returningvoid.- Optional:
long longand%lldwhen values outgrowint.
What is the Fibonacci series?
Starting from 0 and 1, every later term is the sum of the previous two. This tutorial prints terms in that order.
The sequence appears in rabbit models, tiling counts, continued fractions, and algorithm analysis (Fibonacci heaps, matrix powers, and Euclid’s algorithm worst case).
Golden ratio bound
Let φ = (1+√5)/2. Then Fk with the usual nonnegative indexing satisfies Fk ∼ φk / √5 as k → ∞, explaining rapid growth in fixed-width types.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 — matches Example 1 with n = 10.
Intuition
- Update
(a,b)←(b,a+b)
Takeaway: you only need two accumulators to stream the sequence; no array is required for printing.
Live preview
First n terms with 0, 1 seeds. Uses BigInt so long series stay exact in the browser.
Algorithm
Goal: print the first n Fibonacci numbers in order, or every Fibonacci number not exceeding a bound M.
Initialize the pair
Set (first, second) = (0, 1) to match this tutorial’s seed convention.
Iterate
Print first, compute next = first + second, then shift (first, second) ← (second, next). Stop after n prints or when the next value would exceed M.
📜 Pseudocode
function print_first_n_fibonacci_terms(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = next First n terms (n = 10)
Same logic as the reference (displayFibonacci): two-pointer update and terms = 10. Adds n ≤ 0 handling and avoids a trailing comma after the last term.
#include <stdio.h>
void display_fibonacci_terms(int n) {
int first = 0;
int second = 1;
int i;
if (n <= 0) {
printf("Need a positive term count.\n");
return;
}
printf("Fibonacci series up to %d terms: ", n);
for (i = 0; i < n; ++i) {
if (i > 0) {
printf(", ");
}
printf("%d", first);
{
int next = first + second;
first = second;
second = next;
}
}
printf("\n");
}
int main(void) {
int terms = 10;
display_fibonacci_terms(terms);
return 0;
} Explanation
The loop prints the current first before advancing the pair. The comma is printed before every term except the first, which removes the dangling comma the original output showed after 34.
All terms ≤ 100
Same recurrence, different stop rule: keep printing while the current value fits the ceiling. Output uses spaces (no comma run).
#include <stdio.h>
void display_fibonacci_until(int max_val) {
int a = 0;
int b = 1;
int first_out = 1;
if (max_val < 0) {
printf("max_val must be nonnegative.\n");
return;
}
printf("Fibonacci numbers <= %d: ", max_val);
while (a <= max_val) {
if (!first_out) {
printf(" ");
}
first_out = 0;
printf("%d", a);
{
int next = a + b;
a = b;
b = next;
}
}
printf("\n");
}
int main(void) {
display_fibonacci_until(100);
return 0;
} Explanation
The loop condition checks the value about to be printed. The first Fibonacci strictly greater than 100 is 144, so the series stops at 89.
Going faster (optional)
Matrix exponentiation. Computes Fn in O(log n) arithmetic steps using [[1,1],[1,0]] powers—overkill for printing the whole prefix.
Doubling identities. Useful in competitive programming for huge n modulo a prime.
Interview: prefer the O(n) two-pointer loop; mention overflow and why tree recursion is avoided.
❓ FAQ
🔄 Input / output examples
Change terms in Example 1 or max_val in Example 2.
| n (terms) | Last printed (int demo) |
|---|---|
1 | 0 |
2 | 1 (second is the second seed) |
10 | 34 |
47 | would exceed INT_MAX on 32-bit int (use wider type) |
Edge cases and pitfalls
Signed overflow on addition is undefined behavior in C. Once values approach INT_MAX, switch to long long or stop printing.
n ≤ 0
Decide whether to print nothing, an error line, or to treat n = 0 as a valid empty series.
Overflow on next = a + b
Check b > max_val - a (careful with negatives) or widen types before adding.
fib(n) tree
Exponential time if you recompute fib(n-1) and fib(n-2) independently; not suitable for long series.
Counting prints
Clarify whether n counts printed numbers (this page) or iterations after the seeds.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
First n terms (iterative) | O(n) | O(1) |
All terms ≤ M | O(k) prints, k = O(log M) | O(1) |
Naive fib(n) recursion | O(φn) work | O(n) stack |
Here φ is the golden ratio; the exponential bound is the classic analysis of the naive tree.
Summary
- Core loop: print
first, then(first,second)←(second,first+second). - Variants: fixed term count vs values bounded by
M. - Watch-outs:
n ≤ 0, comma formatting, and integer overflow.
The ratio of consecutive values Fk+1/Fk (for positive Fk) approaches the golden ratio φ = (1+√5)/2 as k grows—one reason Fibonacci numbers explode so quickly in fixed-width integers.
8 people found this page helpful
