nCr (combination)
:#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
}
else {
return n * factorial(n-1);
}
}
int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n-r));
}
int main() {
int n, r;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter the value of r: ");
scanf("%d", &r);
if (n < r) {
printf("Invalid input: n should be greater than or equal to r\n");
}
else {
printf("%dC%d = %d\n", n, r, nCr(n, r));
}
return 0;
}
Enter the value of n: 6
Enter the value of r: 5
6C5 = 6
factorial
function is defined to calculate the factorial of a given integer. The nCr function
calculates the combination of n
and r
using the formula n!/(r!(n-r)!)
. main function
prompts the user to enter the values of n
and r
, checks whether n
is greater than or equal to r
, and prints the result of the combination if the input is valid.