Display Fibonacci Series in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Iteration

What You’ll Learn

Fibonacci is a classic interview warm-up: stateful loops, two-variable updates, and careful integer overflow. This tutorial covers the 0, 1 seed definition, an n-term printer, a ceiling variant, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Definition

Seeds 0, 1

Each term is the sum of the previous two: Fk = Fk-1 + Fk-2.

Two Accumulators

(a, b) shift

Stream the series with (a, b) ← (b, a + b) — no array required.

n Terms

Fixed count

Print the first n values with clean comma separators.

Until Cap

Values ≤ M

Same recurrence; stop when the next printed value would exceed M.

Live Preview

BigInt

Generate up to 500 exact terms in the browser — no float rounding.

Overflow

k

Growth is exponential — widen to long long or stop before INT_MAX.

Introduction

Fibonacci series starts from 0 and 1 in this tutorial. Every later term is the sum of the previous two, so the sequence begins 0, 1, 1, 2, 3, 5, 8, 13, …

In C interviews you are usually asked to print the first n terms (or all values up to a ceiling) with a simple loop, discuss overflow, and explain why naive tree recursion is a bad fit for long series.

Why it matters?

It trains stateful loops, careful formatting, and exponential growth awareness — skills that show up in DP warm-ups, tiling counts, and Euclid’s algorithm analysis.

Key Highlights

Seeds 0, 1

This page’s convention; some texts start at 1, 1.

Two Variables

Only the previous pair is needed to stream terms.

Two Stop Rules

Fixed term count, or values bounded by a ceiling.

C Type Limits

Signed int overflows well before 50 terms on 32-bit.

In short: seed (0, 1), print the current value, shift the pair forward, and stop after n terms or when values exceed a bound — prefer iteration over naive recursion.

📝 Problem & Approach

Given a positive term count n (or a ceiling M), print Fibonacci numbers in order using an iterative two-pointer update.

c
/* First 10 terms (conceptual)
 * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
 *
 * Update rule each step:
 *   next = a + b;  a = b;  b = next;
 */

Inputs & Outputs

ItemTypeDescription
n / termsintHow many Fibonacci numbers to print (Example 1).
max_valintCeiling: print every Fibonacci number ≤ max_val (Example 2).
Printed outputtextComma- or space-separated series on one line.

Minimal workflow

Pseudocode
function print_first_n_fibonacci_terms(n):
    a = 0
    b = 1
    repeat n times:
        output a
        next = a + b
        a = b
        b = next

Method comparison

MethodIdeaExtra space
Iterative pairPrint a, then (a, b) ← (b, a + b)O(1)
Naive recursionRecompute fib(n-1) and fib(n-2) independentlyO(n) stack, exponential time

⚡ Quick Reference

GoalPattern
Seed the pairint first = 0, second = 1;
Advance one stepnext = first + second; first = second; second = next;
Avoid trailing commaif (i > 0) printf(", "); then print the value
Stop by ceilingwhile (a <= max_val) { … }
Widen for long seriesUse long long and %lld

📋 Iterative vs Naive Recursion vs Matrix Power

All can produce Fibonacci numbers — but cost differs sharply.

Iterative pair
(a,b) shift

O(n) time, O(1) space — the interview default

Naive fib(n)
tree recursion

Exponential work; avoid for printing a series

Matrix / doubling
O(log n)

Great for a single Fn; overkill for a full prefix

Interview tip
mention overflow

State int limits and why iteration beats tree recursion

Context

When This Problem Shows Up

Reach for Fibonacci drills when stateful loops and growth matter.

  1. Interview warm-ups

    Quick check of loops, formatting, and overflow awareness.

  2. DP precursors

    Each state depends on the previous two — a tiny DP table in disguise.

  3. Tiling & counting

    Ways to tile a board of length n often equal Fibonacci numbers.

  4. Teaching stateful loops

    Clear visual of carrying two variables across iterations.

  5. Not for huge Fn alone

    A single huge term needs matrix/doubling or big integers — not a plain int loop.

Key benefit: one small problem that covers loops, formatting, complexity, and overflow in a short exercise.

🔮 Live Preview

Choose a term count between 1 and 500 and print the series with exact BigInt arithmetic.

Try 1, 15, or 80. Capped at 500 terms for this widget.

Live result
Press “Print series”.

Examples Gallery

Two complete C programs — first n terms, and all values up to a ceiling. Click View Output to reveal sample console results.

📚 Getting Started

Print ten terms with clean comma separators.

Example 1 — First n Terms (n = 10)

Two-pointer update with n ≤ 0 handling and no trailing comma after the last term.

c
#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;
}

How It Works

The loop prints the current first before advancing the pair. The comma is printed before every term except the first, which removes a dangling trailing comma.

📈 Practical Patterns

Same recurrence with a value ceiling instead of a term count.

Example 2 — All Terms ≤ 100

Keep printing while the current value fits the ceiling. Output uses spaces (no comma run).

c
#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;
}

How It Works

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.

🧠 How the Algorithm Prints Terms

1

Seed the pair

Set (first, second) = (0, 1) to match this tutorial’s convention.

Init
2

Print current

Output first (with a separator if it is not the first printed value).

Output
3

Advance

Compute next = first + second, then shift (first, second) ← (second, next).

Update
=

Series complete

Stop after n prints, or when the next value would exceed the ceiling.

🔎 Worked Walkthrough — First 6 Terms

Trace the pair update for n = 6 starting from (0, 1). Each row prints first, then advances.

StepPrintAfter update (first, second)
00(1, 1)
11(1, 2)
21(2, 3)
32(3, 5)
43(5, 8)
55(8, 13)

Printed series: 0, 1, 1, 2, 3, 5.

Use Cases

Where Fibonacci numbers show up beyond the interview prompt.

1. Tiling Counts

Ways to tile a 1×n board with tiles of size 1 and 2.

Example: length 5 → F6 under common indexing.

2. DP Warm-Ups

Builds intuition for states that depend on prior states.

Example: climb stairs taking 1 or 2 steps.

3. Euclid Analysis

Worst-case GCD inputs are consecutive Fibonacci numbers.

Example: Lamé’s theorem.

4. Loop / Format Drills

Practice separators, headers, and stop conditions.

Example: no trailing comma after the last term.

5. Growth & Types

Shows why fixed-width ints fail for long sequences.

Example: switch to long long past ~47 terms.

6. Teaching Recursion Cost

Contrast O(n) iteration with exponential naive fib(n).

Example: whiteboard the call tree for fib(5).

Pro Tip: if the interviewer wants a single Fn for huge n, mention matrix exponentiation; if they want a printed series, ship the O(n) pair loop.

Advantages

Why the iterative pair approach earns interview points.

  1. 1. O(1) Extra Memory

    Two integers stream any length series without storing the whole list.

  2. 2. Linear Time

    Exactly one addition per printed term — optimal for emitting a prefix.

  3. 3. Easy to Explain

    Matches the recurrence on a whiteboard without memoization clutter.

  4. 4. Flexible Stop Rules

    Same loop body works for term counts or value ceilings.

Pro Tip: lead with the pair loop, then mention why naive recursion is exponential if they ask about recursive solutions.

Usage Tips

Small habits that keep Fibonacci code clean in interviews.

  1. 1. Clarify Seed Convention

    Ask whether the series starts 0, 1 or 1, 1 before coding.

  2. 2. Print Separators Before Values

    Avoids trailing commas without special-casing the last iteration.

  3. 3. Prefer Iteration for Series

    Save recursion (with memo) for single-term lookups if needed.

  4. 4. Widen Types Early

    Use long long when n might exceed ~40–47 on 32-bit int.

  5. 5. Validate Term Counts

    Handle n ≤ 0 explicitly — empty series or error message.

Pro Tip: dry-run six steps on paper (table above) before coding — it catches off-by-one print counts fast.

Common Pitfalls

Mistakes that commonly break Fibonacci series solutions in C.

  1. 1. Trailing Comma

    Printing ", " after every value leaves a dangling separator.

    → Print the separator before terms with index > 0.

  2. 2. Signed Overflow UB

    next = a + b is undefined behavior when it exceeds INT_MAX.

    → Widen to long long or stop before overflow.

  3. 3. Naive Tree Recursion

    Recomputing fib(n-1) and fib(n-2) independently is exponential.

    → Use the iterative pair (or memoize) for series output.

  4. 4. Off-by-One Term Counts

    Confusing “print n numbers” with “loop n updates after seeds.”

    → Clarify with the interviewer; this page counts printed values.

  5. 5. Ignoring n ≤ 0

    Zero or negative term counts should not crash or print garbage.

    → Validate early; print nothing or an error line.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single term

Output is just 0 with the 0, 1 seed convention.

n = 2

Both seeds

Prints 0, 1 — the second value is the second seed.

Terms

n ≤ 0

Empty series or error message — match the problem statement.

UB

Overflow on add

Signed overflow is undefined; widen types or stop early.

Ceiling

max_val = 0

Still prints 0 because the seed fits the bound.

Off-by-one

Counting prints

Confirm whether n counts printed numbers or post-seed iterations.

🔄 Sample Values

Known outputs for the fixed-term variant (32-bit int demos).

n (terms)Last printed
10
21 (second seed)
1034
47exceeds INT_MAX on 32-bit int — use wider type

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read n from stdin

  • Use scanf and validate before printing
  • Handle n ≤ 0 with a clear message

2. Use long long

  • Print the first 50 terms safely
  • Switch format to %lld

3. Return an array

  • Fill int arr[n] instead of printing
  • Useful when a judge expects a list

4. nth term only

  • Stop after computing index n without full formatting
  • Mention matrix power as a follow-up for huge n

Notes

  • Growth. Values grow like φk — fixed-width ints overflow quickly.
  • Two accumulators are enough to stream the series; storing every term is optional.
  • Validate n > 0 (or treat zero as empty); confirm seed convention with the prompt.
  • For a single huge Fn, matrix exponentiation or doubling identities beat printing a long prefix.

Quick Takeaway: seed (0, 1), print-and-shift in a loop, prefer O(n) iteration over tree recursion, and watch integer overflow.

⏱️ Time and Space Complexity

TaskTimeExtra space
First n terms (iterative)O(n)O(1)
All terms ≤ MO(k) prints, k = O(log M)O(1)
Naive fib(n) recursionO(φn)O(n) stack

Here φ is the golden ratio; the exponential bound is the classic analysis of the naive call tree.

Wrap Up

🎉 Conclusion

Fibonacci series is a small stateful-loop exercise with big teaching payoff: pair updates, clean formatting, and exponential growth in C integers. Master the fixed-term and ceiling variants so you can adapt either stop rule in an interview.

Practice the two examples above, then continue to GCD for another classic number-theory warm-up.

Seed (0, 1), shift with (a, b) ← (b, a + b), prefer iteration over tree recursion, and widen types before overflow.

💡 Best Practices

✅ Do

  • Confirm seed convention (0, 1 vs 1, 1)
  • Use the O(n) two-pointer loop for series output
  • Validate n > 0 (or handle empty output)
  • Print separators before values to avoid trailing commas
  • Mention overflow and long long when asked about limits

❌ Don’t

  • Use naive tree recursion to print long series
  • Ignore signed overflow on a + b
  • Leave a trailing comma after the last term
  • Skip the n = 1 and n = 2 edge cases
  • Assume every prompt starts at 0

Key Takeaways

Knowledge Unlocked

Five things to remember about Fibonacci in C

Print the series the interview-friendly way.

5
Core concepts
0 02

Seeds

Start at 0, 1 here

Convention
03

Update

(a,b) ← (b, a+b)

Code
04

Overflow

Widen past ~47 terms

C types
O 05

Complexity

O(n) time, O(1) space

Analysis

❓ Frequently Asked Questions

Each term is the sum of the two before it. With seeds 0 and 1, the series begins 0, 1, 1, 2, 3, 5, 8, 13, ...
Yes; some texts start at F1=F2=1. The relative shift only changes indexing; the recurrence is the same after the first few values.
Fibonacci grows exponentially. On typical 32-bit int, values exceed 2^31-1 before 50 terms, so use long long or arbitrary precision for long series.
Naive fib(n) recursion recomputes subproblems and is exponential in n. Iteration (or recursion with memoization) is O(n) time and O(1) extra space for streaming the series.
Printing zero terms is valid: print a header and no numbers, or treat n < 1 as an error depending on the assignment.
O(n) arithmetic steps with the two-pointer update, assuming each addition fits your chosen integer type.
Print the separator before every term except the first (if i > 0 print ", "), instead of printing a comma after each value.
F_k grows like phi^k / sqrt(5), where phi = (1+sqrt(5))/2. That asymptotic explains why fixed-width ints overflow so quickly.

Did you Know? 🔊

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.

Continue to GCD

Learn how to find the greatest common divisor with Euclid’s algorithm in C.

GCD tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful