C Code for Factorial

In Mathematics factorial, is an operation that calculates the product of all positive integers less than or equal to the given number.

Here we are going to see how we can calculate the factorial of a given number in C programming language.

We can calculate the factorial of a given number either by using a loop or by using recursion.

C Code for Factorial Using Loop

#include <stdio.h>
void main()
{
    int n, fact = 1, i = 0;
    printf("Enter the Nmber");
    scanf("%d", &n);
    if (n < 0)
    {
        printf("Invalid Input");
    }
    else if (n == 0)
    {
        printf("Factorial of %d = 1", n);
    }
    else
    {
        for (i = 1; i <= n; i++)
        {
            fact = fact * i;
        }
        printf("Factorial of %d = %d", n, fact);
    }
}

Output

c code for factorial using loop

C Code for Factorial Using Recursion

#include <stdio.h>
int factorial(int n)
{
    if (n == 0 || n == 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1);
    }
}
void main()
{
    int n, fact = 1, i = 0;
    printf("Enter the Number");
    scanf("%d", &n);
    if (n < 0)
    {
        printf("Invalid Input");
    }
    else
    {
        fact = factorial(n);
        printf("Factorial of %d = %d", n, fact);
    }
}

Output

c factorial using recursion

The above C code calculates factorial by calling a recursive function factorial() this function takes number as a input and return number of the factorial.

See Also

10 thoughts on “C Code for Factorial”

Leave a Comment