Write a C program to calculate the factorial of a given number.

Previous
Next
  • Factorial Program in C: Factorial of n is the product of all positive descending integers.
  • Factorial of n is denoted by n!.
  • For example:
    • 5! = 5*4*3*2*1 = 120 
    • 3! = 3*2*1 = 6 

Approach-1:

  • In this approach, we simply write the code in main() function.
  • Read the n value to find the factorial.
  • By iterating the simple loop, we can find the factorial as follows.
#include<stdio.h>  
int main()    
{    
	int i,fact=1,n;    
	printf("Enter n value : ");    
	scanf("%d",&n);    
	for(i=n;i>1;i--)
	{    
		fact=fact*i;    
	}    
	printf("Factorial of %d is: %d \n",n,fact);    
	return 0;  
}   

Approach-2:

  • In this approach, we use the custom function to find the factorial of given number.
  • Custom function takes the ‘n’ value as input and returns the factorial value of that input number.
  • We use for loop to calculate factorial value of input.
#include<stdio.h>  
int factorial(int);
int main()    
{    
	int n;    
	printf("Enter n value : ");    
	scanf("%d",&n);    
	factorial(n);    
	printf("Factorial of %d is: %d \n",n,factorial(n));    
	return 0;  
}   
int factorial(int n)
{
	int i, fact=1;
	for(i=n;i>1;i--)
	{    
		fact=fact*i;    
	}
	return fact;
}
Previous
Next

Courses Enquiry Form