Skip to main content

How Do You Write A Factorial Program In C ?

by
Last updated on 4 min read

What's a factorial?

A factorial is the product of all positive integers up to a given number.

Take 5, for example. 5! means 5 × 4 × 3 × 2 × 1, which equals 120. In C, you can calculate this with a loop, recursion, or the tgamma function from the math library. Just remember—factorials explode in size fast. 20! already blows past 64-bit integer limits, and 100! stretches to 158 digits.

How do you write a factorial program in C?

You write it with a loop, recursion, or the tgamma function.

Start by deciding how you want to approach it. A simple loop works for small numbers (≤20). Recursion is great for learning. And tgamma handles slightly larger values (≤170). Pick your weapon—just keep overflow in mind.

What's the fastest way to get a working factorial in C?

Use this one-liner in GCC 12+:

gcc factorial.c -o factorial -lm && ./factorial

Plug in any integer ≤20 to avoid overflow. For bigger numbers, switch to arbitrary-precision (we’ll cover that later).

What do I need before writing a factorial program?

GCC 12+ or Clang 15+, and the math.h library.

Without these, you’ll hit compilation errors or missing functions. Check your compiler version first. If you’re missing math.h, install it or switch compilers.

Can you show me a simple iterative factorial program in C?

Here’s a loop-based version that handles numbers up to 20 safely.
  1. Create a file named factorial.c.
  2. Paste this code:
    #include <stdio.h>
    
    int main() {
        int n;
        printf("Enter a number (0-20): ");
        scanf("%d", &n);
    
        if (n < 0) {
            printf("Factorial is not defined for negative numbers.\n");
            return 1;
        }
    
        unsigned long long fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
    
        printf("%d! = %llu\n", n, fact);
        return 0;
    }
    
  3. Compile and run: gcc factorial.c -o factorial -lm && ./factorial

How do I write a recursive factorial function in C?

Replace the loop with a function that calls itself.

Here’s the magic:

unsigned long long fact(int n) {
    return (n == 0) ? 1 : n * fact(n - 1);
}

Call fact(n) in your main() function. It’s elegant, but watch out—stack overflows happen if you go too deep (though 20 is safe).

Can I use the tgamma function for factorials?

Yes, but only for numbers up to 170.

tgamma is a gamma function from math.h. The trick? n! = tgamma(n + 1). Here’s the code:

#include <stdio.h>
#include <math.h>

int main() {
    int n;
    printf("Enter a number (0-170): ");
    scanf("%d", &n);
    printf("%d! = %.0f\n", n, tgamma(n + 1));
    return 0;
}

Compile with -lm to link the math library. It’s fast, but precision drops for very large n.

What if my factorial program overflows?

Switch from 64-bit integers to big-integer libraries.

If you’re hitting overflow with n > 20, don’t panic. Replace unsigned long long with a big-integer array or use a library like GMP. That’ll handle numbers with hundreds of digits.

How do I handle negative inputs?

Add validation to reject negative numbers.

Before calculating anything, check if the input is negative. If it is, print an error and exit. Factorials aren’t defined for negatives, so this keeps your program safe.

Why is the math library missing when I compile?

You forgot the -lm flag in GCC/Clang.

That flag links the math library. Without it, the compiler won’t find tgamma or other math functions. Always include -lm when using math.h.

How can I prevent overflow in my factorial program?

Cap inputs at 20 when using 64-bit integers.

Honestly, this is the simplest fix. If you need bigger numbers, switch to arbitrary-precision libraries. Also, test edge cases—0! and 1! both equal 1. Negative numbers? They should trigger an error.

What data types should I use for large factorials?

Use arbitrary-precision libraries or string-based digits.

For n > 20, forget about standard integers. Libraries like GMP handle huge numbers cleanly. Or, if you’re feeling adventurous, implement digit arrays in strings.

What edge cases should I test in a factorial program?

Test 0!, 1!, and negative inputs.

These are the classic traps. 0! and 1! both equal 1. Negative numbers? They should prompt an error message. Don’t skip these—your users will thank you.

Should I document my assumptions in the code?

Yes, always add comments for future maintainers.

Future developers (or even you, six months from now) will appreciate clear notes. Mention limits like “n ≤ 20 for 64-bit” or “uses GMP for n > 20.” It saves headaches later.

Where can I find more help with C programming?

Check the GMP library docs or compiler manuals.

For big integers, GMP is your best friend. For general C help, compiler manuals and Stack Overflow are goldmines. Don’t hesitate to ask—even pros Google constantly.

David Okonkwo
Author

David Okonkwo holds a PhD in Computer Science and has been reviewing tech products and research tools for over 8 years. He's the person his entire department calls when their software breaks, and he's surprisingly okay with that.

What Is An ESEL?How Do You Write A Scientific Name?