This blog is under construction

Saturday 22 June 2013

C program to evaluate the series - 1 - 1/3 + 1/5 - 1/7 +...+ 1/n

Write a C program to evaluate the series   1 - 1/3 + 1/5 - 1/7 +...+ 1/n.



  #include <stdio.h>
  int main() {
        int n, i, sign = 1;
        float res = 0.0;

        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the given series */
        for (i = 1; i <= n; i++) {
                res = res + (sign * (1.0/i));
                sign = sign * (-1);
        }

        printf("Result: %.3f\n", res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:100
  Result: 0.688


No comments:

Post a Comment