0

beginner here trying to understand the source of the bug.

I have written this recursive function for finding the binomial coefficient between two numbers which is apparently correct in concept. However, for these two numbers, n =4 and k=2, I should be getting 6 as a result whereas I actually get 16. Any idea why is that happening?

#include<stdio.h>

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

  return binomial(n - 1, k - 1) + binomial(n - 1, k);
}

int main()    
{
  int a, b, res;
  a = 4;
  b = 2;
  res = binomial(a, b);
  printf("The result is %d", res);
  return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
franx
  • 57
  • 6

2 Answers2

5

This line looks wrong as it assigns 0 to k:

if ((k=0) || (k==n))

You probably mean:

if ((k==0) || (k==n))
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
5

This line

 if ((k = 0) || (k == n))

should be

  if ((k == 0) || (k == n))  
         ^^

You were assigning zero to k.

As @Michael Walz points out, it's good practice to compile with -Wall to turn on all compilation warnings.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541