Recursion is a programming technique where a function calls itself directly or indirectly. You can use it to calculate the factorial of a number. The factorial of negative number is not defined, so the number should be non-negative i.e. >=0. The factorial of 0 and 1 is 1.
Here is the code based on recursion.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 10;
if (num < 0){
printf("Factorial of a negative number is not defined\n");
}
else{
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}
In the above code, the factorial() function calls itself until n becomes 1.