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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int fact(int n) | |
{ | |
if(i<2) | |
return 1; | |
return n*fact(n-1); | |
} | |
void factorial(int n) | |
{ | |
if(n<0) | |
printf("Invalid Number"); | |
else | |
printf("%d",fact(n)); | |
} |
Please let me know if u have any questions .
2 comments:
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
Thanks for ur comment . I will change it .
Post a Comment