Recursion refers to the process where a function calls itself directly or indirectly to solve a problem. It is a powerful tool in programming that allows for elegant solutions to problems that can be broken down into simpler, repetitive tasks. However, it must be used with caution to avoid issues like infinite loops or excessive memory usage.
Here’s a C program to calculate the factorial of a number using recursion:
#include
// Function to calculate factorial using recursion
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
int result = factorial(number);
printf("Factorial of %d is %d\n", number, result);
}
return 0;
}
if (n == 0), which returns 1. This stops the recursion when n reaches 0.n * factorial(n - 1), which calls the function with n - 1 and multiplies the result by n.Enter a positive integer: 5
Factorial of 5 is 120Advantages
Disadvantages