Print the Result
In this step, we will enhance our permutation calculation program by adding more detailed output and formatting options.
Let's modify the permutations.c
file to improve result presentation:
cd ~/project
nano permutations.c
Update the code with improved result printing:
#include <stdio.h>
// Function to calculate factorial
unsigned long long factorial(int num) {
unsigned long long result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
// Function to calculate permutation (nPr)
unsigned long long permutation(int n, int r) {
// Check for invalid input
if (r > n) {
printf("Error: r cannot be greater than n\n");
return 0;
}
// Calculate nPr using the formula: n! / (n-r)!
return factorial(n) / factorial(n - r);
}
// Function to print detailed permutation explanation
void printPermutationDetails(int n, int r, unsigned long long result) {
printf("\n--- Permutation Calculation Details ---\n");
printf("Total number of items (n): %d\n", n);
printf("Number of items selected (r): %d\n", r);
printf("Calculation: %d P %d = %d! / (%d - %d)!\n", n, r, n, n, r);
printf("Result: %llu different arrangements possible\n", result);
printf("----------------------------------------\n");
}
int main() {
int n, r;
printf("Permutation (nPr) Calculator\n");
printf("Enter the total number of items (n): ");
scanf("%d", &n);
printf("Enter the number of items to be selected (r): ");
scanf("%d", &r);
unsigned long long result = permutation(n, r);
if (result > 0) {
printPermutationDetails(n, r, result);
}
return 0;
}
Compile and run the program:
gcc permutations.c -o permutations
./permutations
Example output:
Permutation (nPr) Calculator
Enter the total number of items (n): 5
Enter the number of items to be selected (r): 3
--- Permutation Calculation Details ---
Total number of items (n): 5
Number of items selected (r): 3
Calculation: 5 P 3 = 5! / (5 - 3)!
Result: 60 different arrangements possible
----------------------------------------
Key improvements:
- Added a dedicated
printPermutationDetails()
function
- Included more informative output about the calculation
- Explained the permutation formula and result
- Improved user interface with a title and detailed explanation