You are here:

# C/Small help on a program in c language

Question
Sir,
I made a program for calculating-
1/1!+2/2!+3/3!+4/4!+.....
depending upon the number of terms user enters.
According to me the logic is correct but still i am not getting the correct output.
Here is the code for the same...
#include<stdio.h>
#include<conio.h>
int fact(int),y,i,n;
double k;
void main()
{
clrscr();
printf("enter number of terms");
scanf("%d",&n);
k=0;
for(i=1;i<=n;i++)
{
k=i/fact(i)+k;
k=i/fact(i);
}
printf("%lf",k);

getch();
}
int fact(int n)
{float f;
if(n==1)
return (1);
else
f=n*fact(n-1);
return(f);
}
A quick response regarding the reason of wrong output of the program will be appreciated.

Hi Akash,

There were several things wrong with your code. You were using integer division to determine the value of k, which was rounded down. You should make fact return a double or cast it to a double before using it in division. To sum the result you should use k += ... or k = k + ... inside the for loop. In your recursive fact function there is no need to store the result in f when you can simply return n*fact(n-1). I hope this helps you solve your problem.

Example:
``` #include<stdio.h> double fact(int); void main() {   int i, n;   double k;   printf("enter number of terms:");   scanf("%d",&n);   k=0;   for(i=1;i<=n;i++)   {      k+=(double)i/fact(i);   }   printf("%lf", k);   getchar(); } double fact(int n) {   if(n==1)      return (1);   else      return n*fact(n-1); } ```

C

Volunteer

#### Tony Nazzal

##### Expertise

I will answer any c language programming and syntax questions.

##### Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.