Factorial of a Number in C

The factorial of a non-negative integer n is the product of all positive integers from 1 through n. By definition, 0! = 1.

n! = n × (n - 1) × ... × 2 × 1

Factorial with a for Loop Top ↑

#include <stdio.h>

int main(void) {
    int number;

    printf("Enter an integer from 0 to 20: ");
    if (scanf("%d", &number) != 1 ||
        number < 0 ||
        number > 20) {
        printf("Enter a value from 0 to 20.\n");
        return 1;
    }

    unsigned long long factorial = 1;

    for (int i = 2; i <= number; i++) {
        factorial *= (unsigned long long)i;
    }

    printf("%d! = %llu\n", number, factorial);
    return 0;
}

For input 10, the result is:

10! = 3628800

The upper limit of 20 prevents overflow when unsigned long long is 64 bits, because 21! no longer fits in 64 bits.

Factorial with a Function Top ↑

#include <stdio.h>

unsigned long long factorial_iterative(unsigned int number) {
    unsigned long long result = 1;

    for (unsigned int i = 2; i <= number; i++) {
        result *= i;
    }

    return result;
}

int main(void) {
    unsigned int number = 8;

    printf("%u! = %llu\n",
           number,
           factorial_iterative(number));

    return 0;
}

Recursive Factorial Top ↑

#include <stdio.h>

unsigned long long factorial_recursive(unsigned int number) {
    if (number <= 1) {
        return 1;
    }

    return number * factorial_recursive(number - 1);
}

int main(void) {
    unsigned int number = 6;

    printf("%u! = %llu\n",
           number,
           factorial_recursive(number));

    return 0;
}

Recursion is useful for understanding function calls, but the loop version avoids recursive call overhead and is usually simpler for factorial.

Continue with factors of a number or review functions in C.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer