This blog is under construction

Saturday 13 July 2013

C program to generate exponential series

Write a C program to generate power series.


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

  /* calculate factorial for the given input x */
  double fact(int x) {
        double result = 1.0;
        while (x > 0) {
                result = result * x;
                x--;
        }
        return (result);
  }

  int main() {
        double x, val, result = 1;
        int n, i = 1;

        /* get the value for x from the user */
        printf("Enter the value for x:");
        scanf("%lf", &x);

        /* get the value for n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* print the power series */
        printf("1 ");
        while (i <= n) {
                printf("%s (%.0f^%d)/%d! ", "+",x, i, i);
                val = pow((double)x, (double)i)/fact(i);
                result = result + val;
                i = i + 1;
        }

        /* print the result of the cosine series */
        printf("\nResult: %lf\n", result);
        return 0;
  }


Note:
gcc power.c -lm => link math library since we have used math function pow().

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x:1
  Enter the value for n:6
  1 + (1^1)/1! + (1^2)/2! + (1^3)/3! + (1^4)/4! + (1^5)/5! + (1^6)/6! 
  Result: 2.718056


No comments:

Post a Comment