Factorial of a Number in C [4 Methods]

programming

Summary: In this example, we will learn different ways to find the factorial of a given number in C programming language.

Factorial of any number (n) is given by the following formula:

n*(n-1)*(n-2)*(n-3)......4*3*2*1

We can easily calculate it using the following 4 ways in C:

Method 1: Using While Loop

To calculate factorial of a number using while loop we need to run while loop until n!=0, each time decreasing the value of n by 1 and multiplying the number to the resultant value.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int n, factorial= 1;
    printf("Enter a number \n");
    scanf("%d",&n);
 
    while(n!=0){
        factorial = factorial * n--;
    }
 
    printf("Factorial using While loop: %d",factorial);
 
    return 0;
}

Output:

C Program for Factorial using While Loop

Method 2: Using For Loop

To calculate the factorial of a number using for loop, we run a loop from n to 1 in decrementing order and multiply each number into the factorial product.

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int n, i, factorial= 1;
    printf("Enter a number \n");
    scanf("%d",&n);
 
    for(i=n; i>0; i--){
        factorial = factorial*i;
    }
 
    printf("Factorial using For loop: %d",factorial);
 
    return 0;
}

Output:

C Program for Factorial using for Loop

Method 3: Using Recursion

We can also find the factorial of any positive number using recursion. With base condition n==1, we multiply the number with the next recursive call as n * factorial(n-1).

#include <stdio.h>
#include <stdlib.h>

//recursive function 
int factorial(n){
    if(n==1)
        return 1;
    return n*factorial(n-1);
}
 
int main()
{
    int n;
    printf("Enter a number \n");
    scanf("%d",&n);
 
    printf("Factorial using Recursion: %d",factorial(n));
    return 0;
}

Output:

C Program for Factorial using recursion

Method 4: Using Function

We create a function that applies any of the above three methods to calculate and return the factorial of the passed number as an argument.

#include <stdio.h>
#include <stdlib.h>
 
int factorial(n){
    int factorial= 1;
    for(int i=n; i>0; i--){
        factorial = factorial*i;
    }
    return factorial;
}
 
int main()
{
    int n;
    printf("Enter a number \n");
    scanf("%d",&n);
 
    printf("Factorial using Function: %d",factorial(n));
    return 0;
}

Output:

C Program for Factorial using function

There were four ways using which ae can compute the factorial of any positive number in C programming. Comment below your suggestion.

One thought on “Factorial of a Number in C [4 Methods]”

Leave a Reply

Your email address will not be published. Required fields are marked *