Write a program that implements the following functions iteratively (no recursio
ID: 3796467 • Letter: W
Question
Write a program that implements the following functions iteratively (no recursion). double factorial (int n) double exponent (double x, int n) The functions implemented should follow below guidelines factorial: Computes n! = n times (n -1) x...x 1 exponent: Computes the sum of first n terms of e^x using the following approximation. F(x, n) = e^x = sigma^n = i = 0 x^i/i! = x^0/0! + x^1/2! +...+ x^n/n! You can use pow() and factorial 0 functions in your exponent function. In main () use argc and argu read the value of n and z from the user and compute and print the approximation of e^x for all values up to n using the function exponent. Print the results as a table as shown below. Also, print the exact value of e^x using the math library function exp(). When you increase the value of i your result should get closer to the result of exp. Name your program assign3.c Sample execution of the program is given below. First parameter is n and second parameter is z. You need to use functions atoi f() and atof() in stdlib.h to convert strings to integer and double respectively.Explanation / Answer
// C code
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
double factorial (int n)
{
double fact = 1;
int i;
for (i = 1; i <= n; ++i)
{
fact = fact*i;
}
return fact;
}
double exponent(double x, int n)
{
double result = 0;
int i;
for (i = 0; i <= n ; ++i)
{
result = result + pow(x,i)/factorial(i);
}
return result;
}
int main(int argc, char const *argv[])
{
if(argc < 2)
{
printf("Input arguments missing ");
return 0;
}
int n;
sscanf (argv[1],"%d",&n);
double x;
sscanf (argv[2],"%lf",&x);
int i;
double exponentValue;
printf(" i Approximation ");
printf("---------------------------------- ");
for (i = 0; i <= n; ++i)
{
printf(" %d ", i);
exponentValue = exponent(x,i);
printf("%0.10lf ",exponentValue);
}
printf("Exact Value: %0.10lf ",exponent(x,n));
return 0;
}
/*
output:
i Approximation
----------------------------------
0 1.0000000000
1 3.2000000000
2 5.6200000000
3 7.3946666667
4 8.3707333333
5 8.8002026667
6 8.9576747556
7 9.0071659835
8 9.0207760712
9 9.0241029815
10 9.0248349018
Exact Value: 9.0248349018
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.