Print the Factorial
In this step, you will enhance the factorial calculation program to provide more detailed output and handle different input scenarios. We'll modify the factorial.c
file to improve the presentation of factorial results.
Update the factorial.c
file:
cd ~/project
nano factorial.c
Replace the previous content with the following improved implementation:
#include <stdio.h>
unsigned long long factorialLoop(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
void printFactorialDetails(int n, unsigned long long factorial) {
printf("Factorial Calculation Details:\n");
printf("Number (n): %d\n", n);
printf("Factorial (n!): %llu\n", factorial);
printf("Factorial Expansion: ");
for (int i = 1; i <= n; i++) {
printf("%d%s", i, (i < n) ? " × " : " = ");
}
printf("%llu\n", factorial);
}
int main() {
int n;
printf("Enter a non-negative integer to calculate its factorial: ");
scanf("%d", &n);
if (n < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
return 1;
}
if (n > 20) {
printf("Warning: Factorial for large numbers may cause integer overflow.\n");
}
unsigned long long result = factorialLoop(n);
printFactorialDetails(n, result);
return 0;
}
Compile and run the program:
gcc factorial.c -o factorial
./factorial
Example output:
Enter a non-negative integer to calculate its factorial: 5
Factorial Calculation Details:
Number (n): 5
Factorial (n!): 120
Factorial Expansion: 1 × 2 × 3 × 4 × 5 = 120
Key improvements in this version:
- Added a detailed
printFactorialDetails()
function
- Displays the full factorial expansion
- Includes warning for large numbers
- Provides clear, informative output