# Thread: recursion to find binomial

1. ## recursion to find binomial

hi can someone help me check if my recursion is right? i cant seems to get the answer
Code:
#include<stdio.h>
int getBinomial(int, int);

int main(void)
{
int n,k;
printf("enter :");
scanf("%d %d", &n, &k);
printf("binomial =%d", getBinomial(n,k));

return 0;
}

int getBinomial(int n, int k)
{
while(n>=0)
{
if(k==0 || k==n)
return 1;
}

if(n>k && k>0)
return getBinomial(n-1,k) + getBinomial(n-1, k-1);

}

2. For starts you really do need to learn how to indent code to visually represent what's going on. Both indentation and vertical whitespace make programs far more readable.

Second C is probably the worst name for a function I've ever seen... Give your variables and functions meaningful names... GetBinomial()... etc.

Finally... throw in some diagnostic printf() statements so you can see what's going on... they'll tell you the story.

And, no, I'm not going to compile your code and test it for you...

3. Code:
while(n>=0)
{
if(k==0 || k==n)
return 1;
}
What good can that loop possibly be?

Quzah.

4. Thanks Quzah! i think i just created a infinite loop!
Code:
#include<stdio.h>
int getBinomial(int, int);

int main(void)
{
int n,k;
printf("enter :");
scanf("%d %d", &n, &k);
printf("binomial =%d", getBinomial(n,k));

return 0;
}

int getBinomial(int n, int k)
{
if(k==0 || k==n)
return 1;

if(n>k && k>0)
return getBinomial(n-1,k) + getBinomial(n-1, k-1);

}
It can run now! THANKS!