Loading your workspace…
Loading your workspace…
Read a non-negative integer and print its factorial, the product of all whole numbers from 1 up to it.
#include <stdio.h>
int main(void) {
int n, i;
unsigned long long result = 1;
printf("Enter a non-negative integer (0-20):\n");
if (scanf("%d", &n) != 1 || n < 0 || n > 20) {
printf("Error: enter a value from 0 to 20\n");
return 1;
}
for (i = 2; i <= n; i++) {
result *= i;
}
printf("%d! = %llu\n", n, result);
return 0;
}
Input
5Output
Enter a non-negative integer (0-20):
5! = 120Input
0Output
Enter a non-negative integer (0-20):
0! = 1The loop starts at 2 because multiplying by 1 changes nothing and result already starts at 1. For n = 0 the loop does not run, which gives the defined value 0! = 1.
Factorials grow very fast. 20! is the largest that fits in an unsigned 64-bit integer, which is why the input is limited to 20.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
5
Expected output
Enter a non-negative integer (0-20): 5! = 120
0
Expected output
Enter a non-negative integer (0-20): 0! = 1
1, by convention; it makes the recurrence n! = n × (n - 1)! work for n = 1.
It holds much larger values than int, and 20! is the largest factorial that fits.
21! overflows a 64-bit integer, which would give a wrong answer.
Yes: factorial(n) = n * factorial(n - 1) with factorial(0) = 1.
It prints an unsigned long long value.
Back to all RCU 21BCA1C1P lab programs.