This blog is under construction

Saturday 22 June 2013

C program to evaluate the series 1/1! + 2/2! + 3/3! +...+n/n!

Write a C program to evaluate the series   1/1! + 2/2! + 3/3! +...+ n/n!.


  #include <stdio.h>
  /* calculate factorial for given data - data! */
  int fact(int data) {
        int res = 1;
        while (data > 1) {
                res = res *data;
                data--;
        }
        return res;
  }

  int main() {
        float res = 0.0, i, n;
        printf("Enter the value for n:");
        scanf("%f", &n);

        /* calculate the given series */
        for (i = 1.0; i < n; i = i + 1.0) {
                res = res + (i / fact(i));
        }
        printf("Result: %.3f\n", res);
        return 0;
  }



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



No comments:

Post a Comment