C Example Code2026-03-152 min read
Generate the Fibonacci series in C using iterative loops and recursive functions. Complete code with complexity analysis and output.
What is the Fibonacci Series?
The Fibonacci sequence is a mathematical series where each number is the sum of the two preceding numbers, starting from 0 and 1:
text (ISO Standard)F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)
First 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
1. Iterative Approach (Recommended)
The iterative approach uses a simple loop with O(n) time complexity and O(1) auxiliary space:
c (ISO Standard)#include <stdio.h> void printFibonacciIterative(int n) { long long first = 0; long long second = 1; long long next; printf("Fibonacci Series (%d terms):\n", n); for (int i = 0; i < n; i++) { if (i <= 1) { next = i; } else { next = first + second; first = second; second = next; } printf("%lld ", next); } printf("\n"); } int main() { int terms = 10; printFibonacciIterative(terms); return 0; }
Expected Output
text (ISO Standard)Fibonacci Series (10 terms): 0 1 1 2 3 5 8 13 21 34
2. Recursive Approach
c (ISO Standard)#include <stdio.h> long long fibonacci(int n) { if (n <= 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int terms = 10; printf("Fibonacci Series via Recursion:\n"); for (int i = 0; i < terms; i++) { printf("%lld ", fibonacci(i)); } printf("\n"); return 0; }
Complexity Comparison
| Method | Time Complexity | Auxiliary Space | Notes |
|---|---|---|---|
| Iterative | O(n) | O(1) | Optimal for practical performance |
| Recursive | O(2ⁿ) | O(n) (Call Stack) | Demonstrates recursive branching |
Related Tutorials & Examples
- Understand recursion in Functions in C Programming.
- Review loop syntax in C Programming Basics.
- Try more math examples like Prime Number Program in C.