WAP to compute permutation and combination values using function.
WAP to compute permutation and combination values using function.
Answer: write a factorial function and two functions that use it: \(^nP_r = \dfrac{n!}{(n-r)!}\) and \(^nC_r = \dfrac{n!}{r!\,(n-r)!}\).
#include <stdio.h>
long long fact(int n) {
long long f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}
long long permutation(int n, int r) {
return fact(n) / fact(n - r);
}
long long combination(int n, int r) {
return fact(n) / (fact(r) * fact(n - r));
}
int main() {
int n, r;
printf("Enter n and r: ");
scanf("%d %d", &n, &r);
if (n < 0 || r < 0 || r > n) {
printf("Invalid input: need 0 <= r <= n\n");
return 0;
}
printf("nPr = %lld\n", permutation(n, r));
printf("nCr = %lld\n", combination(n, r));
return 0;
}
Explanation: fact() returns \(n!\). permutation() and combination() call it with the right arguments and return the results to main(), which only reads input and prints. Using functions avoids repeating the factorial loop three times. long long is used because factorials grow quickly (values are exact up to 20!).
Sample run: n = 6, r = 2 gives nPr = 30 and nCr = 15.
Log in or create a free account to answer this question.