Please answer in a detailed and easy to read manner. Please code in java! Thank
ID: 3862839 • Letter: P
Question
Please answer in a detailed and easy to read manner. Please code in java! Thank you.
The binomial coefficient C(n, k) can be calculated using the recurrence relation:
C(n, k) = C(n-1, k) + C(n-1, k-1) for 0 < k < n
C(n, 0) = 1 for any n = 0 to n.
C(k, k) = 1 for any k = 0 to n.
Write an iterative program to compute the binomial coefficient C(n, k) using the recurrence relation and the basic conditions given above.
As part of your asnwer, include the COMPLETE program code (in java) as well as a screenshot of the output for the n and k values.
n = 12
k = 9
Explanation / Answer
BinomialCoefficient.java
import java.util.Scanner;
public class BinomialCoefficient {
public static void main(String[] args) {
//Declaring variables
int n,k;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//Getting the value of n entered by the user
System.out.print("Enter the value of n :");
n=sc.nextInt();
//Getting the value of k entered by the user
System.out.print("Enter the value of k :");
k=sc.nextInt();
//calling the method by passing the n and k as arguments
int coeff=findBinCoefficient(n,k);
//Displaying the coefficient
System.out.printf(" Value of C(%d, %d) is %d ", n, k,coeff);
}
/* this method will calculate the binomial coefficient based on n and k value
* Params n,k value of type integer
* return binomial coefficient of type int
*/
private static int findBinCoefficient(int n, int k) {
if (k==0 || k==n)
return 1;
else
return findBinCoefficient(n-1, k-1) + findBinCoefficient(n-1, k);
}
}
_________________
Output:
Enter the value of n :12
Enter the value of k :9
Value of C(12, 9) is 220
__________Thank You