Answer in brief
For a non-negative integer n, n! is the product of integers from 1 through n. By definition, 0! equals 1.
Algorithm
- Read n and accept values from 0 through 20.
- Set factorial to 1.
- Multiply factorial by each integer i from 2 through n.
- Print factorial.
Worked trace
For n = 5, factorial starts at 1. Multiplication by 2 gives 2; by 3 gives 6; by 4 gives 24; and by 5 gives 120. When i becomes 6, the test fails and the program prints 120.
Boundary cases
For n = 0 or n = 1, the loop body is skipped and the result remains 1. Negative integers are rejected because this program uses the elementary factorial definition. The program does not attempt a factorial above 20, because factorial grows rapidly and a fixed-width integer cannot store arbitrary results.
Data type choice
unsigned long long can represent at least the range needed for 20!. The format %llu matches that type. Choosing a wider type does not remove every limit; it only increases the supported range. An input must still be representable by the type used to read it.
Time and space complexity
For n >= 2, the loop performs n - 1 multiplications. The number grows linearly with n, giving O(n) time for this algorithm under fixed-width arithmetic. The input bound is a safety limit on the example. The program stores a fixed number of values, so auxiliary space is O(1).
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n;
unsigned long long factorial = 1;
if (scanf("%d", &n) != 1 || n < 0 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 2; i <= n; ++i) {
factorial *= (unsigned long long)i;
}
printf("Factorial = %llu\n", factorial);
return 0;
}
Sample input and output
Input
5
Output
Factorial = 120