I have written a program with 2 functions which compute factorials & combinations. The functions work perfectly when called but I cannot insert a for loop at the end which sums up the combos. This part works (I have omitted the functions because they work when called for).

long factorial(int n);
long combination(int n, int k);
int main ()
{
    int n=0,k=0;
 
    while(n<=0)
    {
        printf("Enter value for n:");
        scanf("%i", &n);
        if(n<=0)
            printf("Please enter a positive integer value for n.\n");
    }
 
    while(k<=0||k>n)
    {
        printf("Enter value for k:");
        scanf("%i", &k);
        if(k<=0)
            printf("Please enter a positive integer value for k.\n");
        else if (k>n)
            printf("k must be less than or equal to n.\n");
    }
 
    long f = factorial(n);
    long c = combination(n,k);
 
    printf("n! = %i\n", f);
    printf("C(n,k) = %i\n", c);
    system("pause");
    return 0;
}

But when I insert this piece of code in the main body it goes haywire.

unsigned long sum=0;
int i;
for(i=0;i<=n;i++)
{
sum+=combination(n,i);
}
printf("sum=%un",sum);

What am I doing wrong? The sum of the combos should equal 2^n.
thanks!:eek:

Factorial values may easily go out of hand and overflow due to their exponential nature. So if you insert very high values of "n" the output might overflow.

Please paste your output along with the input you giving, along with the function combination def. (just in case).

Also dont use system("pause") to stop the screen. Use getchar() to achieve the same function.

Long values are printed using the format specifier %ld which i dont see in your program.

Nothing more can be said unless you post your combination function along with the input which you supplied to it.

Thanks, s.o.s. I will change the specifier to ld and system("pause").
My 2 functions are below in code. I will change the specifiers on those as well to prevent overflow.
I place the value "6" for n & "2" for k & I get display
"n! = 720
C(n,k) = 15"
which are both correct.
I want "n" to be fixed & then I want the summation of the combo to go from 0 to n for k/i.
Thank you for reading.

long factorial(int n) 
{
    if (n<0)
        return MATH_FUNCTION_ERROR;
    else if(n==0)
        return 1;
    else
    {
        long result=1;
        int i;
        for(i=1;i<=n;i++)
            result*=i;
        return result;
    }
}
//returns (n!)/(k!*(n-k)!)
long combination(int n, int k) 
{
    if(n>=k)
        return factorial(n)/(factorial(k)*factorial(n-k));
    else
        return MATH_FUNCTION_ERROR;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.