Is Recursion better than a Loop? It depends.
Recursion is often cleaner to write and easier to read (especially for trees). But it comes at a cost: Space Complexity.
- Iteration: Uses 1 Stack Frame. It just updates a variable in a loop. Space is $O(1)$.
-
Recursion: Uses N Stack Frames. If you calculate
factorial(10000), you push 10,000 frames onto memory. Space is $O(N)$.
If you go too deep, recursion crashes (Stack Overflow). Iteration runs forever.
The Code
Here I implemented Factorial in both ways to compare the syntax.
// Day 9: The Two Paths
#include <stdio.h>
// Method 1: Recursive (The Elegant Way)
// Risks: Stack Overflow for large numbers
unsigned long long factorial_rec(int n) {
if (n <= 1) return 1;
return n * factorial_rec(n - 1);
}
// Method 2: Iterative (The Efficient Way)
// Benefits: Uses constant memory (No stack growth)
unsigned long long factorial_iter(int n) {
unsigned long long res = 1;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
int main() {
int num = 5;
printf("Recursive: %llu\n", factorial_rec(num));
printf("Iterative: %llu\n", factorial_iter(num));
return 0;
}
📂 View the source code on GitHub: https://github.com/Ujjawal0711/30-Days
Top comments (0)