Find the Factorial of a Number by Recursive Method.


/*
Write a program in to find the factorial of a number by recursive method.
*/


#include<stdio.h>

long int fact(int n);
long int Iterfact(int n);
main( )
{
 int num;

 printf("Enter a number : ");
 scanf("%d", &num);

 if(num<0)
 printf("No factorial for negative number\n");
 else
 printf("Factorial of %d is %ld\n", num, fact(num) );

 if(num<0)
 printf("No factorial for negative number\n");
 else
 printf("Factorial of %d is %ld\n", num, Iterfact(num) );
}

/*Recursive*/
long int fact(int n)
{
 if(n == 0)
 return(1);
 return(n * fact(n-1));
}


/*Iterative*/

long int Iterfact(int n)
{
 long fact=1;
 while(n>0)
 {
 fact = fact*n;
 n--;
}
 return fact;
}


Post a Comment

0 Comments