How to Get Sum of Series 1-1/2+1/3-1/4+….1/n in C Program
It is easy to get sum of series 1 – 1/2 + 1/3 – 1/4 + . . . 1/n in C program. In this tutorial, I’ll show you how to do it in easy way in C program. Here is a simple code for it:
#include <stdio.h>
int main()
{
int n,i;
float s=0.0;
printf(“Enter the value of n of the series: “);
scanf(“%d”,&n);
printf(“Sum of the series: “);
for (i =1; i <= n; i++)
{
s=s+1.0/(i*1.0)*pow(-1.0,i+1);
if(i==1)
printf(“%d – “,i);
else if(i>=n)
printf(“1/%d = %f “,i,s);
else
if(i%2==0)
printf(“1/%d + “,i);
else
printf(“1/%d – “,i);
}
return 0;
}
Output:
Enter the value of n of the series: 10
Sum of the series: 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 - 1/8 + 1/9 - 1/10 = 0.645635
In this tutorial, I have shown how to get sum of series 1 – 1/2 + 1/3 – 1/4 + . . . + 1/n in C Program. Hope you have enjoyed the tutorial. If you want to get updated, like the facebook page http://www.facebook.com/freetechtrainer and stay connected.