Calculate the series 1 + 1/2! + 1/3! + ..upto N terms C Program

How to write a program to calculate the series 1 + 1/2! + 1/3! + ...upto N terms in C Programming ?


Solution:
/*Write a program to calculate the series 1 + 1/2! + 1/3! + .. upto N terms. Note: Factorial is just to the denominator */

int fact(long double n)   // Factorial function -> arguments "long double" because it should return long float
{
long double i,fac=1;
//printf("enter the range of factorial");       // these comment lines are used to check the factorial program
//scanf("%lf",&n);

for(i=1;i<=n;i++)
{
fac=fac*i; // recursive function
}
// printf("%lf \n",fac);
return fac;
}


int main()
{
int n,i;
long double sum=0,r=0;
printf("Enter the range for series");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
r=fact(i); // GCC compiler shows error if command is 'sum+=(1/fact(i))'; so r is required
sum+=(1/r);

}
printf("the sum of series is %.18Lf \n",sum); //.18Lf stands for long float upto 18 decimals
     
return(0);
}


Learn More :