This blog is under construction

Saturday 13 July 2013

C program to generate cosine series

Write a C program to generate cosine series.


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

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

  int main() {
        double x, val, res = 1;
        int n, i = 2, sign = -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 cosine series */
        printf("1 ");
        while (i <= n) {
                printf("%s (%.0f^%d)/%d! ", sign < 0 ? "-":"+",x, i, i);
                val = sign * pow((double)x, (double)i)/fact(i);
                res = res + val;
                sign = sign * -1;
                i = i + 2;
        }

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


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

  Output:
  jp@jp-VirtualBox:~/$ gcc cosine.c -lm
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x:1
  Enter the value for n:10
  1 - (1^2)/2! + (1^4)/4! - (1^6)/6! + (1^8)/8! - (1^10)/10! 
  Result: 0.540302


No comments:

Post a Comment