Recursive Combination in C

A batchmate had invited me to code this recursively, as short as possible. Actually writing the code I understood how one can make basic mistakes even after the concepts are known. Eg. I clean forgot to write a non-recursive escape condition to the recursive calls. Which lead to a segmentation fault and my subsequent quests into why it was a “Segmentation fault” though calls are stored in the “Stack” in memory.

Here’s the program.


#include<stdio.h>

float comb(float, float);
static int count;

int main()
{

float a, b;
printf(“Enter two numbers: \n”);
scanf(“%f%f”, &a, &b);
printf(“\n%f”, comb(a,b));
printf(“\n%d”, count);
return 0;
}

float comb(float n, float k){

if(k==1)
{
count++;
return n;
}
count++;
return (n/k)*comb(n-1, k-1);

}

The static count was there to see that for trial values of (8, 4) there were 4 recursive calls. A suggested logic used integer variables only … and needed 139 calls to compute the same trial values. *smug look*

Advertisements

About Aruni RC

Engineering student, IT.Programming and fantasy, sci-fi enthusiast.

Posted on April 21, 2010, in C, programming. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: