C# Program to Print Fibonacci Series
for (int i = 0, a = 0, b = 1; i < n; i++) { Console.Write(a + " "); int c = a + b; a = b; b = c; }.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int n = 10; int a = 0, b = 1; for (int i = 0; i < n; i++) { Console.Write(a + " "); int c = a + b; a = b; b = c; } } }
Dry Run
Let's trace printing the first 5 Fibonacci numbers through the code.
Initialize
a = 0, b = 1, i = 0
Print and Calculate
Print 0, c = 0 + 1 = 1, a = 1, b = 1, i = 1
Print and Calculate
Print 1, c = 1 + 1 = 2, a = 1, b = 2, i = 2
Print and Calculate
Print 1, c = 1 + 2 = 3, a = 2, b = 3, i = 3
Print and Calculate
Print 2, c = 2 + 3 = 5, a = 3, b = 5, i = 4
Print and Calculate
Print 3, c = 3 + 5 = 8, a = 5, b = 8, i = 5 (stop)
| Iteration | a | b | Printed Number |
|---|---|---|---|
| 0 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 |
| 3 | 2 | 3 | 2 |
| 4 | 3 | 5 | 3 |
Why This Works
Step 1: Start with first two numbers
We begin with a = 0 and b = 1 because the Fibonacci series starts with 0 and 1.
Step 2: Print current number
Each loop prints the current number stored in a before calculating the next.
Step 3: Calculate next number
The next Fibonacci number is the sum of the previous two, so we compute c = a + b.
Step 4: Update variables
We move forward by setting a = b and b = c to prepare for the next iteration.
Alternative Approaches
using System; class Program { static int Fibonacci(int n) { if (n <= 1) return n; return Fibonacci(n - 1) + Fibonacci(n - 2); } static void Main() { int n = 10; for (int i = 0; i < n; i++) { Console.Write(Fibonacci(i) + " "); } } }
using System; class Program { static void Main() { int n = 10; int[] fib = new int[n]; fib[0] = 0; if (n > 1) fib[1] = 1; for (int i = 2; i < n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } foreach (int num in fib) { Console.Write(num + " "); } } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, so the time grows linearly with the number of Fibonacci numbers requested.
Space Complexity
Only a few variables are used, so space stays constant regardless of n.
Which Approach is Fastest?
The iterative loop method is fastest and most memory efficient compared to recursion or array storage.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Fast and memory efficient for printing series |
| Recursive method | O(2^n) | O(n) | Simple code but slow for large n |
| Array storage | O(n) | O(n) | When you need to access all numbers later |