C++ Program to Print Fibonacci Series
0 and 1. For example: int a=0, b=1; for(int i=0; i prints the first n Fibonacci numbers. Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int n; cin >> n; int a = 0, b = 1; for (int i = 0; i < n; i++) { cout << a << " "; int next = a + b; a = b; b = next; } return 0; }
Dry Run
Let's trace input 5 through the code
Initialize variables
a = 0, b = 1
Iteration 1
Print 0, next = 0 + 1 = 1, a = 1, b = 1
Iteration 2
Print 1, next = 1 + 1 = 2, a = 1, b = 2
Iteration 3
Print 1, next = 1 + 2 = 3, a = 2, b = 3
Iteration 4
Print 2, next = 2 + 3 = 5, a = 3, b = 5
Iteration 5
Print 3, next = 3 + 5 = 8, a = 5, b = 8
| Iteration | a | b | Printed Number |
|---|---|---|---|
| 1 | 0 | 1 | 0 |
| 2 | 1 | 1 | 1 |
| 3 | 1 | 2 | 1 |
| 4 | 2 | 3 | 2 |
| 5 | 3 | 5 | 3 |
Why This Works
Step 1: Start with first two numbers
The Fibonacci series always begins with 0 and 1, so we set a = 0 and b = 1.
Step 2: Print current number
In each loop, we print the current number stored in a because it represents the next number in the series.
Step 3: Calculate next number
We find the next Fibonacci number by adding the last two numbers: next = a + b, then update a and b to move forward.
Alternative Approaches
#include <iostream> using namespace std; int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cout << fib(i) << " "; } return 0; }
#include <iostream> using namespace std; int main() { int n; cin >> n; int fib[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]; } for (int i = 0; i < n; i++) { cout << fib[i] << " "; } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, each step does constant work, so total time is O(n).
Space Complexity
Only a few variables are used to store numbers, so space is O(1).
Which Approach is Fastest?
The iterative loop method is fastest and uses least memory 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 but slow, not for large n |
| Array storage | O(n) | O(n) | When series needs to be reused or accessed randomly |