Easy Tutorial
❮ C Examples Dynamic Memory Allocation Largest C Function Rand ❯

C Language Example - Factorial

C Language Examples

The factorial of a positive integer (English: factorial) is the product of all positive integers less than or equal to that number, and the factorial of 0 is 1. The factorial of a natural number n is written as n!.

n! = 1 × 2 × 3 × ... × n. The factorial can also be defined recursively: 0! = 1, 1! = 1, n! = (n-1)! × n.

Example

#include <stdio.h>

int main()
{
    int n, i;
    unsigned long long factorial = 1;

    printf("Enter an integer: ");
    scanf("%d", &n);

    // Display error if the input is negative
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");

    else
    {
        for(i = 1; i <= n; ++i)
        {
            factorial *= i; // factorial = factorial * i;
        }
        printf("%d! = %llu", n, factorial);
    }

    return 0;
}

Output:

Enter an integer: 10
10! = 3628800

Example - Using Recursion

#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);
    printf("%d! = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n)
{
    if (n > 1)
        return n * multiplyNumbers(n - 1);
    else
        return 1;
}

C Language Examples

❮ C Examples Dynamic Memory Allocation Largest C Function Rand ❯