C Program to Print Fibonacci Series
0 and 1. For example: int a=0, b=1, next; for(int i=0; i prints the first n Fibonacci numbers. Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int n = 10, a = 0, b = 1, next; for (int i = 0; i < n; i++) { printf("%d ", a); next = a + b; a = b; b = next; } return 0; }
Dry Run
Let's trace printing the first 5 Fibonacci numbers through the code.
Initialize variables
n=5, a=0, b=1
Iteration 1
Print a=0; next=0+1=1; a=1; b=1
Iteration 2
Print a=1; next=1+1=2; a=1; b=2
Iteration 3
Print a=1; next=1+2=3; a=2; b=3
Iteration 4
Print a=2; next=2+3=5; a=3; b=5
Iteration 5
Print a=3; next=3+5=8; a=5; b=8
| Iteration | a (printed) | b | next |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 1 | 2 |
| 3 | 1 | 2 | 3 |
| 4 | 2 | 3 | 5 |
| 5 | 3 | 5 | 8 |
Why This Works
Step 1: Start with first two numbers
The Fibonacci series begins with 0 and 1, so we set a=0 and b=1.
Step 2: Print current number
We print the current number a in each loop iteration to show the series.
Step 3: Calculate next number
The next Fibonacci number is the sum of the last two, so we compute next = a + b.
Step 4: Update variables
We then update a to b and b to next to move forward in the series.
Alternative Approaches
#include <stdio.h> int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main() { int n = 10; for (int i = 0; i < n; i++) { printf("%d ", fib(i)); } return 0; }
#include <stdio.h> int main() { int n = 10, fib[10]; fib[0] = 0; fib[1] = 1; for (int i = 2; i < n; i++) { fib[i] = fib[i-1] + fib[i-2]; } for (int i = 0; i < n; i++) { printf("%d ", fib[i]); } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, so the time complexity is O(n). Each iteration does constant work.
Space Complexity
Only a few variables are used to store numbers, so space complexity is O(1).
Which Approach is Fastest?
The iterative loop approach 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 |
| Recursive | O(2^n) | O(n) | Simple code but slow for large n |
| Array storage | O(n) | O(n) | When series needs to be reused |