This blog is under construction

Thursday, 11 July 2013

C program to generate sine series

Write a C program to generate sine series.


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

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

  int main() {
        double x, val, tmp, res = 0, pi = 3.14;
        int n, i = 1, sign = 1;

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

        tmp = x;
        printf("\nSine Series:\n");
        /* sine series evaluation */
        x = (x * 3.14) / 180;

        /* print and calculate the sine series */
        while (i <= n) {
                printf("((3.14/180)^%d)((%.0lf^%d)/%d!) ", i, tmp, i, i);
                val = sign * pow((double)x, (double)i)/fact(i);
                res = res + val;
                sign = sign * -1;
                i = i + 2;
                if (i <= n)
                        printf("%c ", sign < 1 ? '-':'+');
        }
        /* print the sine series output */
        printf("\nResult: %lf\n", res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/02_control_flow$ ./a.out
  Enter the value for x:2
  Enter the value for n:6

  Sine Series:
  ((3.14/180)^1)((2^1)/1!) - ((3.14/180)^3)((2^3)/3!) + ((3.14/180)^5)((2^5)/5!) 
  Result: 0.034882



No comments:

Post a Comment