# Factorial using Recursion

Saurabh | Mar 07, 2010 | Comments 7

As a simple rule of recursion, any function can be computed using a recursive routine if :

1. The function can be expressed in its own form.

2. There exists a termination step, the point at which f(x) is known for a particular ‘x’.

Therefore to write a recursive program for the factorial of any number, we have to express the factorial function in a recursive form using the above 2 rules :

1. fact(n) = fact(n-1)*n (recursive definition of factorial).

2. if n=1, return 1 (termination step).

Using these 2 rules, the recursive program of factorial can be coded very easily as shown :

```
#include "stdio.h"
fact(int n)
{ int factorial;
if(n==1)
return 1;
else
factorial=fact(n-1)*n;
return factorial;
}
main()
{ int num,factorial;
printf("Enter any number : ");
scanf("%d",&num);
factorial=fact(num);
printf("The factorial of %d is %d ",num,factorial);
return 0;
}
```

**About the Author**: Software Engineer - Search & Recommendation at Rovi

I believe I found a bug.

0! is a special case and should evaluate to 1.

#include “stdio.h”

fact(int n)

{ int factorial;

//if(n==1) breaks down for 0!

if(n==0)

return 1;

else

factorial=fact(n-1)*n;

return factorial;

}

I believe factorial 0 has no physical significance and hence have omitted that case.

However, I accept I should have put constraints for 0 and negative numbers.

thanx…because of i have understand recursion program

In my point of view, factorial without using recursion is more simple method that this method

The snippet is not just meant for finding factorial, but for understanding the concept of recursion by an example of finding factorial.

/* Calculate factorial by using recursion */

#include

#include

int fact(int n)

{

if(n==0)

return 1;

else

return n*fact(n-1);

}

void main()

{

int num;

clrscr();

printf(“\n Enter a number :”);

scanf(“%d”,&num);

printf(“\n Factorial value=%d”,fact(num));

getch();

}

Sir please attach the algorithm too …..