# Binomial Coefficient using Dynamic Programming

«
»

This is a C++ Program that Solves Binomial Coefficients Problem using Dynamic Programming technique.

Problem Description

Given two values n and k, find the number of ways of chosing k objects from among n objects disregarding order.

The problem can be rephrased as finding the binomail coefficient C(n,k).

Problem Solution

The problem is to find C(n,k). But this might turn out to be inefficient. So, we will find the binomial coefficient rather than finding C(n,k) by calculating factorials. We can find the binomial coefficient in the same way as we build the pascal’s triangle proceeding in a bottom up fashion.

Expected Input and Output

Case-1:

```n=3, k=2
Expected result=3```
Program/Source Code

Here is source code of the C++ Program to Solve Binomial Coefficients Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
1. `#include<iostream>`
2. `using namespace std;`
3. ` `
4. `int binomialCoefficient(int n, int k)`
5. `{`
6. `    int dp[n+1][k+1];`
7. ` `
8. `    int i,j;`
9. ` `
10. `    for(i=0;i<=n;i++)`
11. `    {`
12. `        for(j=0;j<=i && j<=k;j++)`
13. `        {`
14. `            if(j==0 || j==i)`
15. `                dp[i][j]=1;`
16. ` `
17. `            else`
18. `                dp[i][j]=dp[i-1][j-1]+dp[i-1][j];`
19. `        }`
20. `    }`
21. ` `
22. `    return dp[n][k];`
23. `}`
24. ` `
25. `int main()`
26. `{`
27. `    int n, k;`
28. `    cout<<"Enter the total number of objects "<<endl;`
29. `    cin>>n;`
30. ` `
31. `    cout<<"Enter how many elements to be chosen out of "<<n<<" objects "<<endl;`
32. `    cin>>k;`
33. ` `
34. `    if(n<0 ||k<0 || k>n)`
35. `        cout<<"Invalid input";`
36. ` `
37. `    else`
38. `    {`
39. `        cout<<"The number of ways in which selections can be made is "<<endl;`
40. `        cout<<binomialCoefficient(n,k);`
41. ` `
42. `    }`
43. ` `
44. `    cout<<endl;`
45. `    return 0;`
46. `}`
Program Explanation

In the main function, we ask the user to input the value for number of objects to be chosen and the total number of objects. We pass these values to the function binomialCoefficient as parameters. This function will calculate the expected result and return it. The returned value will be displayed.

Runtime Test Cases
```
Case-1:
\$ g++ binomial_coefficient.cpp
\$ ./a.out
Enter the total number of objects
3
Enter how many elements to be chosen out of 3 objects
2
The number of ways in which selections can be made is
3```

Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions. 