factorial in c using recursion
Here is an example of how to calculate factorial in C using recursion:
#include <stdio.h>
int factorial(int n) {
// Base case
if (n == 0 || n == 1) {
return 1;
}
// Recursive case
else {
return n * factorial(n - 1);
}
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is %d", number, factorial(number));
return 0;
}
This code defines a recursive function factorial
that takes an integer n
as input and returns the factorial of n
. The base case is when n
is 0 or 1, in which case the function returns 1. In the recursive case, the function calls itself with n
decremented by 1, and multiplies the result by n
. This process continues until the base case is reached.
In the main
function, the user is prompted to enter a number. The factorial
function is then called with the entered number, and the result is printed.
This code demonstrates the use of recursion to calculate the factorial of a number in C.