Write a recursive function to calculate binomial coefficients. This function sho
ID: 640524 • Letter: W
Question
Write a recursive function to calculate binomial coefficients. This function should take in two integer arguments, n and k, and will return an integer.
The simplest way to write this code is to have a function named binomial_coefficient() that returns the integer that represents the binomial coefficient. It could look like this:
int binomial_coefficient (int n, int k) {
....
if (n == k) {
....
return .... ;
}
else if () {
....
return .... ;
}
else {
....
return .... ;
}
}
The function will need to check if n is equal to k (and return 1), if k equals 0 (and return 1), or if we need to recursively call the binomial_coefficient function. n should be greater than or equal to zero and k should be greater than or equal to zero AND less than or equal to n
Explanation / Answer
int binomial_coefficient (int n, int k) {
if (n == k) { //The function will need to check if n is equal to k (and return 1),
return 1;
}
else if (k==0) { //if k equals 0 (and return 1),
return 1;
}
else {
return binomial_coefficient(n-1,k-1)+binomial_coefficient(n-1,k); //or if we need to recursively call the binomial_coefficient function.
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.