# Thread: combination(math) function and if statement help

1. ## combination(math) function and if statement help

Basically i wrote a factorial function that works like a charm and planned on using it in this combination function that I wrote. But some of the combinations (nCr) that I need to use have a 0 value for r. This means that somewhere in the calculation I am dividing by zero which gives me an error. I tried to put in an if statement so that if r == 0 to output 1 instead but it is just outputtong random ints instead of 1. Here it is:
Code:
```int nCr (int n, int r)
{
if (r!=0) //if r is not 0 do the calculation and store it.
{
long double nCr = factl(n)/(factl(r)*factl(n-r));
}

else //otherwise store the value 1 instead.
{
int nCr = 1;
}

}```
instead of getting 1 i am getting 4288548 in my output. Any help would be greatly appreciated.

2. change int nCr = 1;
to nCr = 1;

When you use "int" again you are creating a new local variable. (Local to the section in brackets>)

3. i removed it and got 2 compile errors.

factl.h:28: assignment of function `nCr(int, int)'
factl.h:28: assignment to `int ()(int, int)' from `int'

line 28 is the line that i removed int from.

4. Shoot! That's what I get for trying to answer a question when I'm not at my compiler (and maybe not reading carefully). Sorry.

It looks like you're trying to use nCR as both a function and as a variable.

Do you want that function nCR to return 1 under the divide by zero condition?

Just change that line to return 1;

You also need to return a value if you're not dividing by zero
maybe return factl(n)/(factl(r)*factl(n-r));

5. yup that did it, thanks!
im new to making my own functions, we havent learned it in my intro. to programming class yet and i was just fooling around with it.
Thanks again