Here we are going to write a program to find factorial of a number in c using recursion. Earlier we have done this program in two ways. C Program to find factorial of a number and C Program to find factorial of a number using function. Now we will do it using recursion.
Factorial Number: A factorial number is the product of all the number from 1 to the given number.
We represent factorial by '!' .
Example -
n! = n x (n-1) x (n-2) x ....... x 1
5! = 5 x 4 x 3 x 2 x 1 = 120
4! = 4 x 3 x 2 x 1 = 24
3! = 3 x 2 x 1 = 6
There is one exceptional case in factorial and that you must know. Factorial of 0 i.e., 0! = 1, not 0.
What is Recursion?
Recursion occurs when a function calls itself within a function as a result it is called repeatedly. It solves smaller subproblems of original problem.
Now lets do the program. But before going down I will suggest you to first try it on your own and then see the solution.
Program to find factorial of a number in c using recursion
#include <stdio.h>
int fact(n){
if(n==0) return 1;
else if(n==1) return 1;
else return n*fact(n-1);
}
int main(){
int n;
printf("Enter a number: ");
scanf("%d",&n);
int f=fact(n);
printf("Factorial : %d",f);
return 0;
}Output
Enter a number: 5
Factorial : 120
Post a Comment
If you have any doubts, please let me know