Display Fibonacci Series in C#

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Loop & recursion

What you’ll learn

  • The Fibonacci rule: each term is the sum of the two before it, usually starting 0, 1.
  • An iterative C# program that prints the first n terms with two rolling variables.
  • A recursive way to fetch the nth Fibonacci value, plus why memoization matters for bigger inputs.

Overview

Fibonacci is a classic interview warm-up: it tests loops, variable swapping, and whether you know when recursion needs help. The series grows fast, so honest solutions also mention input validation and integer overflow.

Two programs

Iterative print for the first 10 terms and recursive nth lookup with validation.

Live preview

Type how many terms you want and see the sequence update instantly.

Interview realism

Compare O(n) loop vs naive O(2^n) recursion and when to mention memoization.

Prerequisites

Basic C# methods, for loops, and integer variables.

  • C# basics: using System;, static void Main(), Console.WriteLine, string interpolation.
  • Comfort swapping two variables each loop iteration to roll the sequence forward.

What is the Fibonacci series?

The Fibonacci sequence is a list of numbers where each new value equals the sum of the two values before it. With the usual start 0, 1, the series continues 1, 2, 3, 5, 8, 13, 21, ...

You will see Fibonacci in dynamic-programming introductions, nature patterns, and as a gentle recursion exercise. In C# interviews, the loop version is the answer most interviewers want first.

F(5) 5
Rule F(n)=F(n-1)+F(n-2)
Start 0, 1

Formal definition

Let F(0) = 0 and F(1) = 1. For n ≥ 2, define F(n) = F(n-1) + F(n-2). Printing “the first n terms” means outputting F(0) through F(n-1) in order.

First 10 terms

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

Quick patterns

3 + 5 8
Next
Sum of previous two
Term 7 8
Count
0-based index in code

Takeaway: keep two variables for the last two values and walk forward — no array required for printing.

Live preview

Enter how many terms to print (1–30 for this demo). Values use JavaScript numbers; very large terms may exceed safe integer range.

Try 5, 10, or 15. Terms must be a positive integer.

Live result
Press “Show series” to generate the Fibonacci sequence.

Algorithm

Goal: print the first n Fibonacci terms starting from 0, 1.

Validate

Require n ≥ 1 for a term count. Reject zero or negative counts with a message.

Seed values

Set first = 0 and second = 1. These are the first two Fibonacci numbers.

Loop and advance

Print first, compute next = first + second, then shift: first = second, second = next. Repeat n times.

📜 Pseudocode

Pseudocode
function printFibonacci(n):  // n >= 1
    first = 0
    second = 1
    repeat n times:
        print first
        next = first + second
        first = second
        second = next
1

Iterative Fibonacci series

Matches the classic reference: DisplayFibonacci prints the first terms values using a for loop and two rolling integers. Sample run uses terms = 10.

c#
using System;

class Program
{
    static void DisplayFibonacci(int n)
    {
        if (n <= 0)
        {
            Console.WriteLine("Term count must be positive.");
            return;
        }

        int first = 0, second = 1, next;

        Console.Write($"Fibonacci series up to {n} terms: ");

        for (int i = 0; i < n; ++i)
        {
            Console.Write($"{first}, ");
            next = first + second;
            first = second;
            second = next;
        }

        Console.WriteLine();
    }

    static void Main()
    {
        int terms = 10;
        DisplayFibonacci(terms);
    }
}

Explanation

Each iteration prints the current first value, then advances the pair forward. After ten prints you have walked from F(0) through F(9).

next = first + second;

Core rule. The next Fibonacci value is always the sum of the previous two.

first = second; second = next;

Shift. Slide the window one step ahead without storing the entire array.

2

Recursive nth Fibonacci value

Returns F(n) using the recurrence directly. Fine for tiny n in demos; mention memoization or a loop when interviewers ask about performance.

c#
using System;

class Program
{
    static long FibonacciAt(int n)
    {
        if (n < 0)
            throw new ArgumentOutOfRangeException(nameof(n), "Index cannot be negative.");

        if (n == 0) return 0;
        if (n == 1) return 1;

        return FibonacciAt(n - 1) + FibonacciAt(n - 2);
    }

    static void Main()
    {
        int index = 10;
        long value = FibonacciAt(index);
        Console.WriteLine($"Fibonacci at index {index} is: {value}");
    }
}

Explanation

Base cases n == 0 and n == 1 stop the recursion. For larger n the method splits into two smaller subproblems — elegant on paper, expensive without caching.

Optimizing for larger inputs

Memoization. Cache each F(k) in a dictionary or array so recursion visits each index once — time drops to O(n).

Matrix exponentiation. Advanced interviews may ask for O(log n) techniques; the loop remains the practical default.

Interview: write the loop first, state complexity honestly, then offer memoization if they push on huge n.

❓ FAQ

A sequence where each term is the sum of the two before it. The usual start is 0, 1, then 1, 2, 3, 5, 8, 13, and so on.
That matches the classic definition F(0)=0 and F(1)=1, so F(n)=F(n-1)+F(n-2) for n>=2. Some puzzles start with 1,1 instead — always state which convention you use.
For printing n terms or finding the nth value, a simple loop runs in O(n) time with O(1) extra space. Naive recursion recalculates the same values and blows up to O(2^n) time.
A count of terms should be a positive integer. Validate input and print a clear message instead of running a meaningless loop.
Fibonacci numbers grow quickly. By around term 47, values exceed int.MaxValue; use long or BigInteger for bigger n in real programs.
Theta(n) to print n terms: one loop iteration per term with constant work inside.

🔄 Input / output examples

Change terms in the iterative program or index in the recursive sample. For interactive input: int terms = int.Parse(Console.ReadLine()); after validation.

Terms / indexOutput
1 term0,
2 terms0, 1,
5 terms0, 1, 1, 2, 3,
index 10F(10) = 55

Edge cases and pitfalls

Small mistakes in counting terms or picking start values are common — state your convention clearly.

Count

terms = 0

Printing zero terms is meaningless; validate and exit early.

Start

1, 1 vs 0, 1

Some puzzles skip zero. Match the problem statement before coding.

Overflow

Large n

Use long or BigInteger when values outgrow 32-bit int.

Recursion

Naive duplicate work

FibonacciAt(35) without memoization feels sluggish — that is expected.

⏱️ Time and space complexity

VersionTimeExtra space
Iterative print n termsO(n)O(1)
Naive recursive F(n)O(2^n)O(n) stack
Recursive + memoO(n)O(n) cache

The loop is the standard interview answer; recursion shines only after you discuss caching or base-case discipline.

Summary

  • Definition: F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2).
  • C#: use a loop with first and second to print terms; recursion finds a single index but needs memoization at scale.
  • Next step: practice common divisors or dynamic-programming follow-ups.
Did you know?

The Fibonacci sequence shows up outside homework: petal counts, pinecones, and spiral shells often approximate Fibonacci ratios. In interviews the loop version proves you can track state with two variables instead of storing the whole series.

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.

7 people found this page helpful