This blog is under construction

Saturday 13 July 2013

C program to find the sum of infinite series

Write a C program to generate infinite series and find its sum.


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

  int main() {
        int i = 1, n, power;
        float sum = 0.0;

        /*
         * get the number of elements 
         * needed in infinte series
         */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of infinite series */
        while (i <= n) {
                printf("+ 1/(2^%d)", i);
                sum = sum + 1.0 / pow(2, i);
                i++;
        }

        /* print the result */
        printf("\nResult: %f\n", sum);
        return 0;
  }


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

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


No comments:

Post a Comment