5! = 5*4*3*2*1 = 120
Checkout: Factorial without recursion
Solution:
Recursion is the process in which functions calls itself until some base condition is met. Recursion helps in writing shorter functions by dividing a problem into small parts and then solving that problem using a same function again.
We know that n! = 1 for n = 0, n! = n * (n-1)! for n > 0
For writing a recursive method we can use base condition when n become 1 and call the recursive method with (n-1) at each call.
#include<stdio.h>
int factorial(int n) {
if(n>0) {
return n * factorial(n-1);
}
else {
return 1;
}
}
int main()
{
int num =5;
printf("Factorial of %d : %d", num, factorial(num));
}
Output:
Factorial of 5 : 120