Recursion is a process in which a function calls itself to solve a smaller part of the problem. It’s commonly used for tasks that can be divided into similar sub-tasks like calculating factorials, traversing trees, or solving puzzles.
What is Recursion in C?
A recursive function is a function that calls itself, either directly or indirectly, to solve a problem.
#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 result = factorial(5);
printf("Factorial = %d\n", result);
return 0;
}
Output:
Factorial = 120
How Recursion Works (Step-by-Step for factorial(3))