Factorial of a number using Recursion
Let Fact (n) be the function which calculates the factorial of n
If n=0, then n! =1
Fact (n) =
If n>0, then n! =n. (n-1)!
that is, Fact (6) =6*Fact(5)
Fact (5) =5*Fact (4)
Fact (4) =4*Fact (3)
Fact (3) =3*Fact (2)
Fact (2) =2*Fact (1)
Fact (1) =1*Fact (0)
Fact (1) =1*1=1
Fact(2) =2*1=2
Fact (3) =3*2=6
Fact (4) =4*6 =24
Fact (5) =5*24=120
Fact (6) =6*120=720
Write a program to calculate the factorial of the given number by using the recursion function.
#include<stdio.h>
#include<conio.h>
int fact(int num)
{
if(num==0)
return(1);
else
return(num*fact(num-1));
}
void main()
{
int num;
int factorial;
clrscr();
printf("Enter any number to calculate factorial:");
scanf("%d",&num);
factorial=fact(num);
printf("Factorial is:%d",factorial);
getch();
}
Output: Enter any number to calculate factorial:6
Factorial is: 720