Calculate a Factorial
The factorial of n is the product of every positive integer through n.
What is Calculate a Factorial?
The factorial of n is the product of every positive integer through n.
Calculate a factorial with an iterative loop.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int number = 6; unsigned long long result = 1;
// Multiply each value into the running product.
for (int value = 2; value <= number; ++value) result *= value;
printf("%d! = %llu\n", number, result);
}
6! = 720
C++
main.cpp
#include <iostream>
int main() {
int number = 6; unsigned long long result = 1;
// Multiply each value into the running product.
for (int value = 2; value <= number; ++value) result *= value;
std::cout << number << "! = " << result << '\n';
}
6! = 720
C and C++ comparison
Starting the accumulator at one also gives the correct result for zero factorial.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.