- Next
- Sum of previous two
Display Fibonacci Series in C#
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
nterms 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.
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.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Quick patterns
- 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.
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
function printFibonacci(n): // n >= 1
first = 0
second = 1
repeat n times:
print first
next = first + second
first = second
second = next 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.
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.
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.
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
🔄 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 / index | Output |
|---|---|
1 term | 0, |
2 terms | 0, 1, |
5 terms | 0, 1, 1, 2, 3, |
index 10 | F(10) = 55 |
Edge cases and pitfalls
Small mistakes in counting terms or picking start values are common — state your convention clearly.
terms = 0
Printing zero terms is meaningless; validate and exit early.
1, 1 vs 0, 1
Some puzzles skip zero. Match the problem statement before coding.
Large n
Use long or BigInteger when values outgrow 32-bit int.
Naive duplicate work
FibonacciAt(35) without memoization feels sluggish — that is expected.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
Iterative print n terms | O(n) | O(1) |
Naive recursive F(n) | O(2^n) | O(n) stack |
| Recursive + memo | O(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, andF(n)=F(n-1)+F(n-2). - C#: use a loop with
firstandsecondto print terms; recursion finds a single index but needs memoization at scale. - Next step: practice common divisors or dynamic-programming follow-ups.
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.
7 people found this page helpful
