Index « Previous Next »

Question

Compute the sum up to n terms in the series
1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n
where n is a positive integer and input by user.

Source Code

#include <stdio.h>

int main()
{
  int i, n, sign =  - 1;
  float sum = 0;
  
  printf("Enter the value of n : ");
  scanf("%d", &n);

  for (i = 1; i <= n; i++)
  {
    sign *=  - 1;
    sum += sign * 1.0 / i;
  }
  
  printf("The sum of series : %f", sum);

  return 0;
}

Output

Enter the value of n : 10
The sum of series : 0.645635