Saturday, February 16, 2013

Simple Recursive Program to find factorial of a given number in C



Finding factorial of a given number is very easy . Recursive code is given below . Consider you are passing a value 5 to this function .
so its execution will be
5*factorial(4)
5*4*factorial(3)
5*4*3*factorial(2)
5*4*3*2*factorial(1)
5*4*3*2*1
=120

Code: (in C)

Please let me know if u have any questions .

2 comments:

Unknown said...

Small error it seems
waste of recursive call for n==1..
so change the base condition as
if(n<1) return 1;
else return n*fact(n-1);

and also for negative integers recursive call wont stop :P
http://en.wikipedia.org/wiki/Factorial

Dhinakaran said...

Thanks for ur comment . I will change it .