Recursion is a programming technique in which a function calls itself repeatedly to solve a problem. In C programming language, recursion can be used to simplify the code and make it easier to understand in cases where the problem can be divided into smaller, simpler sub-problems.
A recursive function consists of two parts: the base case and the recursive case. The base case is the simplest case that can be solved without recursion. The recursive case is the case in which the function calls itself with a smaller input to solve the problem.
Here is an example of a recursive function that calculates the factorial of a number:
int factorial(int n) {
if (n == 0) { // Base case: factorial of 0 is 1
return 1;
} else { // Recursive case: call factorial with a smaller input
return n * factorial(n - 1);
}
}
In this example, the factorial() function calculates the factorial of a given number n. The base case is when n is 0, in which case the function returns 1. In the recursive case, the function calls itself with a smaller input of n - 1 and multiplies the result by n.
For example, the factorial of 5 can be calculated as follows:
int result = factorial(5); // 5! = 5 * 4 * 3 * 2 * 1 = 120
printf("Factorial of 5 is %dn", result);
In this example, the factorial() function is called with an input of 5, and the result is 120, which is the factorial of 5.
Recursion can be a powerful programming technique when used correctly, but it can also be inefficient and lead to stack overflow errors if not used carefully. It is important to ensure that the recursive function eventually reaches the base case to avoid an infinite loop. Additionally, large recursive function calls can cause the call stack to grow too large, resulting in a stack overflow error.