program to find factorial of a number in c

In this example, we take one integer input from user and return factorial of number

What is Factorial?

Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 5 is 5*4*3*2*1 which is 120.

Factorial can be calculated using following recursive formula.

	
        n! = n * (n-1)!
        n! = 1 if n = 0 or n = 1
    

C Program to Find Factorial of a Number using For Loop

	
#include <stdio.h>

int main()
{
    double c, n, f = 1;

    printf("Enter a number to calculate its factorial\n");
    scanf("%lf", &n);
    for (c = 1; c <= n; c++)
    {
        f = f * c;
    }
    printf("Factorial of %d = %.2lf\n", n, f);   
    return 0;
}
	

Output :

	
Enter a number to calculate its factorial 
10
Factorial of 10 = 3628800.00
	

C Program to Find Factorial of a Number using While Loop

	
#include <stdio.h>

int main()
{
    double i=1, n, f = 1;
    
    printf("Enter a number to calculate its factorial\n");
    scanf("%lf", &n);

    while (i <= n)
    {
    f = f * i;
    i++;
    }
    printf("Factorial of %lf = %.2lf\n", n, f);
    
    return 0;
}
	

Output :

	
Enter a number to calculate its factorial 
5
Factorial of 5 = 120.00
	

What is Recursion?

In computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time.

C Program to Find Factorial of a Number using Recursion

	
#include<stdio.h>
int fact(int);
int main()
{
    int x,n;
    printf(" Enter the Number to Find Factorial ::");
    scanf("%d",&n);
    
    x=fact(n);
    printf(" Factorial of %d is %d",n,x);
    
    return 0;
}
int fact(int n)
{
    if(n==0)
        return(1);
    return(n*fact(n-1));
}
	

Output :

	
Enter the Number to Find Factorial ::10
Factorial of 10 is 3628800
	

Share your thoughts

Ask anything about this examples