Home / Programs / C Program - to find the factorial of a number by both the recursive method and Iterative Method
Programming Example

C Program - to find the factorial of a number by both the recursive method and Iterative Method

👁 16,934 Views
💻 Practical Program
📘 Step by Step Learning
Program to find the factorial of a number by both the recursive method and Iterative Method

Program Code

#include<stdio.h>
long int fact(int n);
long int Ifact(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, Ifact(num) );
}/*End of main()*/


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


/*Iterative*/
long int Ifact(int n)
{
	long fact=1;
	while(n>0)
	{
		fact = fact*n;
		n--;
	}
return fact;
}/*End of ifact()*/

Output

Enter a number : 5
Factorial of 5 is 120
Factorial of 5 is 120
Press any key to continue . . .

Explanation

Recursive Method

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

Iterative Method

/*Iterative*/
long int Ifact(int n)
{
	long fact=1;
	while(n>0)
	{
		fact = fact*n;
		n--;
	}
return fact;
}/*End of ifact()*/

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.