Day 9: Iteration vs. Recursion: Analyzing Performance (Factorial)
Source: Dev.to
Recursion vs. Iteration
Recursion is often cleaner to write and easier to read (especially for trees), but it comes at a cost: space complexity.
-
Iteration uses a single stack frame; it simply updates a variable in a loop.
Space: (O(1)) -
Recursion uses (N) stack frames. For example, calculating
factorial(10000)pushes 10,000 frames onto memory.
Space: (O(N))
If the recursion depth becomes too large, it can crash with a stack overflow, whereas an iterative loop can continue indefinitely.
Implementation in C
// Day 9: The Two Paths
#include
// Method 1: Recursive (The Elegant Way)
// Risks: Stack overflow for large numbers
unsigned long long factorial_rec(int n) {
if (n
}