views:

136

answers:

5

how to get the value of an integer x, indicated by x!, it is the product of the numbers 1 to x.

Example: 5! 1x2x3x4x5 = 120.

int a , b = 1, c = 1, d = 1; 
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
     printf("%d x ", c);
     c++;
     d = d*a;
}
printf(" = %d", d);
+6  A: 

how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.

Did you mean factorial of x ?

Change d = d*a; to d = d*b inside the loop

Prasoon Saurav
And you can printf() and multiply to the same variable also! They are quite flexible and will not perish from shared usage.
blaze
+4  A: 

You can simply do:

for(b = 1; b <= a; b++) {
  d *= b;
}
// d now has a!
codaddict
+2  A: 

Try

d = d * b;

instead of

d = d * a

and it should work fine

Patrice Bernassola
A: 

You actually have a lot of redundant code there, that might be why you did not spot the error yourself.

To calculate the factorial, you only need the accumulator (d in the above code) and the input (a). Why?

Christoffer
+3  A: 

This is the optimal implementation in size and speed:

int factorial(int x)
{
    static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
    if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
    else return INT_MAX+1; /* or your favorite undefined behavior */
}

Hint: x! (x factorial) does not fit in an int except for very very small values of x.

R..
Excellent answer! I'm glad someone pointed out that critical overflow issue.
JoshD