This is what I have so far. This program should contain a recursive function that will compute the binomial coefficient according to the definition if k=0 or k=n

``````#include <iostream>
#include <algorithm>

using namespace std ;

int C(int n,int k)
{

if (k < 0 || k > n )
return 0;
if (k == 0 && n == 0)
return 1;
else return C(n -1,k) + C(n -1,k -1);
}

int main(){``````

## All 6 Replies

I've tested it and it seems to come out ok (against a site like http://www.ohrt.com/odds/binomial.php). What trouble are you having with it?

I have got it to the point where there are no errors. How should I go about printing the output.

In main, declare 2 int variables n and k. Get input from the user using cin or initialize them when you declare them.
Use a statement like `cout << C(n,k)<<endl;` which will call your function and output the results returned from the function. Your recursion will take care of all the subsequent calls the main program just sits and waits for the return.

This is the code I currently have after taking your advice I am currently getting 2 warnings and am not sure why.

``````// This program will contain a recursive function that will compute the binomial coefficient according to the definition if k=0 or k=n

#include <iostream>
#include <algorithm>

using namespace std ;

int C(int n,int k);

int main(){
int n,k;

C(n,k);

cout<< C(n,k) <<endl;

system("PAUSE");
return 0;

}
int C(int n,int k)
{

if (k < 0 || k > n )
return 0;
if (k == 0)
return 1;
if (k == n)
return 1;
else return C(n -1,k) + C(n -1,k -1);
}``````

What were the specific warnings you got?

Please use the code tags when posting the code. You're not getting n and k from anywhere so they are undefined. Either prompt the user for them or declare them like `int n=5,k=3;`. You don't need that first `C(n,k);` in there on line 15 or so, as your function is being evaluated as part of the statement with cout.

Other little things, you don't need to include <algorithm> since you're not using any of its methods. Instead of `System("Pause");` `use cin.get()`. System as call has to halt the program, bring up the OS, run the command, and then bring up your program again. Plus `cin.get` is portable.