đ Recursion in C Programming
Recursion is a technique where a function calls itself to solve a smaller instance of the same problem. It’s widely used for problems like factorial, Fibonacci, tree traversal, etc.
đ What is Recursion?
A recursive function is a function that calls itself during its execution. The recursive call helps to break down complex problems into simpler sub-problems.
đ§ Structure of a Recursive Function
- Base Case: Condition where the recursion stops.
- Recursive Case: Function calls itself with a smaller input.
void recursiveFunction() {
if (base_condition) {
return; // base case
} else {
recursiveFunction(); // recursive case
}
}
đ Example 1: Factorial using Recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1; // base case
else
return n * factorial(n - 1); // recursive call
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
đ§Ē Sample Output:
Enter a number: 5 Factorial of 5 is 120
đ Example 2: Fibonacci Series using Recursion
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int i, n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for(i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
đ§Ē Sample Output:
Enter the number of terms: 6 Fibonacci Series: 0 1 1 2 3 5
⚠️ Important Points
- Every recursive function must have a base case.
- Without a base case, it leads to infinite recursion (stack overflow).
- Recursion is memory-intensive due to function call stack.
⚖️ Recursion vs Iteration
Recursion | Iteration |
---|---|
Function calls itself | Uses loops (for, while) |
More memory usage | Less memory usage |
Elegant and clean code | Faster and more efficient |
đ§Š Practice Problems
- Write a recursive function to calculate the sum of first N natural numbers.
- Check if a string is a palindrome using recursion.
- Find the GCD (Greatest Common Divisor) of two numbers recursively.
- Count the number of digits in a number using recursion.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ