Recursion in C language
In the C programming language, recursion is a technique where a function continually invokes itself until a particular termination condition is satisfied. Recursion is the technique of solving a problem by decomposing it into smaller subproblems and solving each subproblem using the same approach or putting it another way.
Example:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
int main() {
int num = 5;
int result = factorial(num);
printf("The factorial of %d is %d\n", num, result);
return 0;
}
Output:
The factorial of 5 is 120
In this example, the factorial function calculates the factorial of the input number n. If n is 0, the function returns 1, since the factorial of 0 is 1. Otherwise, it calculates the factorial recursively by calling itself with the argument n-1 and multiplying the result by n. The main function calls factorial with the input number 5, and the result is printed to the console.