# Need help with calculating a sum :/

This is a discussion on Need help with calculating a sum :/ within the C Programming forums, part of the General Programming Boards category; As I'm informed about the rules, I won't ask you to write all of the code.. The problem i am ...

1. ## Need help with calculating a sum :/

As I'm informed about the rules, I won't ask you to write all of the code.. The problem i am trying to overcome is that:
Write a program that approximates e by computing the value of :
e=1+1/1!+1/2!+1/3!....+1/n! (user will enter the value "n")

So, my code is as it's written below;
But results are not satisfying when i execute the program.. I ask you to find my mistake and inform me about it. Thanx.

Code:
```#include <stdio.h>
int main ()
{
int k, n, x;
float total, denom;
scanf("%d", &n);
k=1;
denom=1;
total=1;
while(n>=k){
x=n;
for(;x>0; x--){
denom=denom*x;
}

total+=1.0f/denom;
n--;
}
printf("Result:%.4f\n", total);
return 0;
}```

2. You need to set denom to 1 inside the loop.

3. Try using a debugger, or at a push, some debug print statements.
Code:
```    while(n>=k){
x=n;
for(;x>0; x--){
denom=denom*x;
}
printf("Fact(%d)=%f\n",n,denom);

total+=1.0f/denom;
n--;
}```
Are these factorials?

4. OMG ! I spent my 2 days just for this I'm so grateful sir. Thank you very much "qny" !

5. No need for nested loops. If you do insist on nesting the loops, reset denom to 1 at the beginning of the while loop.

6. Originally Posted by Salem
Try using a debugger, or at a push, some debug print statements.
Code:
```    while(n>=k){
x=n;
for(;x>0; x--){
denom=denom*x;
}
printf("Fact(%d)=%f\n",n,denom);

total+=1.0f/denom;
n--;
}```
Are these factorials?
Yes Salem. My first loop (while) for the sum of (1/denom)s, and the second one (for) for factorials.. And thanx for your reply.

7. Yes Grumpy, maybe it is as you said sir. But consider that i am a beginner in c programming approach as you can understand from my coding. And i've learned until loops, that's why I insist on using nested loops. Thanks for your reply.

Popular pages Recent additions