Exercise. 3.7 Write a program which, given a positive integer n and a real number x, returns the value of ex.
   Ex = 1 + x/1 + x2/2! +...+xn/n!

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <math.h>

void e(int, float);
unsigned long int fact(int);

int main(int argc, char **argv) {
    int n;
    float x;

    printf("Enter a positive integer n: ");
    scanf("%d", &n);
    printf("\nEnter a real number x: ");
    scanf("%f", &x);
    e(n, x);
    return 0;
}

void e(int n, float x) {
    float res = 0;
    if (x == 0) {
        res = 1;
        printf("Answer: %f\n", res);
        exit(1);
    } else {
        for (int i = 0; i <= n; i++)
            res += pow(x, i)/fact(i);
        printf("Answer: %f\n", res);
    }
}

unsigned long int fact(int n) {

    if (n == 0)
        return 1;
    else
        return n*fact(n-1);

}

When you compile and execute the above program it produces the following result on Linux:

Enter a positive integer n: 20
Enter a real number x: 1
Answer: 2.718282

Brief Explanation

  • When x is 1, the program calculates the value of e (euler's number) using the series 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + 1/6! + 1/7! + ... (etc).
  • The function e takes two parameters (n and x). If x is 0, the function prints 1 as the result otherwise it iteratively computes xn/n! for values of n from 0 to n. At each iteration, a temporal result is added and assign to the variable res.
  • Once the loop is exited, the value of res is printed to the stdout.
  • The function makes use of the build-in function pow which is defined in the library math.h

Add comment


Security code
Refresh