Skip to content
Circuit

Factorial in C

Loops

Multiply a sequence of integers with a bounded loop and handle zero factorial.

Complete program

#include <stdio.h>

int main(void) {
    int n;
    unsigned long long result = 1;
    printf("n (0 to 20): ");
    if (scanf("%d", &n) != 1 || n < 0 || n > 20) return 1;
    for (int i = 2; i <= n; ++i) result *= (unsigned)i;
    printf("%d! = %llu\n", n, result);
    return 0;
}

Try in Circuit →

Opens a new program without replacing your saved code. Press Run when you are ready.

How it works

The product starts at one, the identity for multiplication. Each iteration multiplies by the next factor. For zero or one, the loop does not execute and the result remains one.

The upper bound is deliberate: 20! fits in unsigned long long, while 21! does not fit in a 64-bit value. Increasing the bound requires a different representation, not merely a longer loop.

Sample input

5

Enter these values when prompted. The transcript below includes typed responses.

Expected output

n (0 to 20): 5
5! = 120

Concepts to practice

  • for loops
  • Accumulator
  • Integer overflow

Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.