This blog is under construction

Saturday, 22 June 2013

C program to evaluate sine series

Write a C program to evaluate 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, res = 0;
        int n, i = 1, sign = 1;
        printf("Enter the value for x:");
        scanf("%lf", &x);
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* sine series evaluation */
        x = (x * 3.14) / 180;
        while (i <= n) {
                val = sign * pow((double)x, (double)i)/fact(i);
                res = res + val;
                sign = sign * -1;
                i = i + 2;
        }

        printf("Result: %lf\n", res);
        return 0;
  }


Note: gcc sine.c -lm  => linking math function for pow() function

  Output:

  jp@jp-VirtualBox:~/$ gcc sine.c -lm
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x:1
  Enter the value for n:100
  Result: 0.017444



No comments:

Post a Comment