The Program in C to use a function that compute the binomial coefficient is given below:
#include <stdio.h>
unsigned long long int factorial(unsigned int n) {
// Function to calculate factorial of a number
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
unsigned long long int binomial_coefficient(unsigned int n, unsigned int k) {
return factorial(n) / (factorial(k) * factorial(n - k));
}
int main() {
unsigned int n, k;
printf("Enter the value of n: ");
scanf("%u", &n);
printf("Enter the value of k: ");
scanf("%u", &k);
printf("Binomial coefficient (n choose k) is: %llu", binomial_coefficient(n, k));
return 0;
}
Output:
Enter the value of n: 4
Enter the value of k: 3
Binomial coefficient (n choose k) is: 4
Pro-Tips💡
This program defines a function binomial_coefficient()
that takes in two parameters n
and k
representing the binomial coefficient.
Inside the function, it calls a helper function factorial()
which takes in one parameter and returns the factorial of the number passed as the parameter using recursion.
The function binomial_coefficient()
uses the formula n!/((k!) (n-k)!) to calculate the binomial coefficient by calling the helper function factorial()
twice.
In the main function, the program prompts the user to enter the values of n
and k
,
and then calls the binomial_coefficient()
function with the inputted values as arguments and the result is printed on the console.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.