Recursion V/S Iteration
Published by: Anil K. Panta
Recursion vs Iteration
In programming, there are two ways to repeat tasks and solve problems step-by-step:
Recursion → A function calls itself
Iteration → A set of steps is repeated using loops (like for or while)
Let’s understand both with an easy example and compare their differences.
Example: Finding Factorial of a Number
The factorial of a number (n!) is the product of all natural numbers from 1 to n.
For example,
5! = 5 × 4 × 3 × 2 × 1 = 120
Program Using Recursion
#include <stdio.h>
int factorialUsingRecursion(int n) {
if (n == 0)
return 1; // Base case
return n * factorialUsingRecursion(n - 1); // Recursive call
}
Program Using Iteration
int factorialUsingIteration(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i; // Loop-based multiplication
}
return res;
}
int main() {
int num = 5;
printf("Factorial of %d using Recursion is: %d\n", num,
factorialUsingRecursion(num));
printf("Factorial of %d using Iteration is: %d", num,
factorialUsingIteration(num));
return 0;
}
Output:
Factorial of 5 using Recursion is: 120
Factorial of 5 using Iteration is: 120
Difference Between Recursion and Iteration
Here is a simple comparison table:
Final Thought
Recursion is great for solving complex, logic-based problems like tree traversals and puzzles.
Iteration is faster and more memory-efficient for most everyday coding tasks.