Code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
double factorial(int num); /*function to compute factorial of a no.*/
int main()
{
int terms;
int i;
double eCalc=0; /*to store the calculated value of e*/
double e=2.718281828458;
double difference;
do
{
printf("Enter no. of terms (n): ");
scanf("%d",&terms);
}
while(terms<=0); /*continue to loop until a positive value is entered*/
for(i=0; i<=terms ; i++)
{
eCalc+=double(1)/factorial(i); /*using formula e = 1/0! + 1/1! + 1/2! + ... + 1/n!*/
}
difference = fabs(e - eCalc);
printf("\nThe approximate value of e : %.12f",e);
printf("\nCalculated mathematical constant e : %.12f",eCalc);
printf("\nThe difference is : %.12f",difference);
/*the .12 after the % signs specifies that there are 12 decimal*/
/*places*/
getch();
}
double factorial(int num) /*recursive function to compute factorial*/
{
if(num==1||num==0) /*the factorial of zero is also 1, it's a mathematical rule!*/
{
return 1;
}
/*the control won't reach the following line if the above*/
/*condition becomes true as the 'return' would also exit*/
/*the function*/
return num * factorial(num - 1);
}