Home C Language Basic C Programs Harmonic series in c

Harmonic series in c

Write a program in C to display the n terms of harmonic series and their sum.
1 + 1/2 + 1/3 + 1/4 + 1/5 … 1/n terms.

#include <stdio.h>

void main()

{

   int i,n;

   float s=0.0;

   printf(“Input the number of terms : “);

   scanf(“%d”,&n);

   printf(“\n”);

   for(i=1;i<=n;i++)

   {

      if(i==1)

      {

         printf(“%d”,i);

         s+=i;

         continue;

      }

      printf(” + 1/%d”,i);

      s+=1/(float)i;

   }

   printf(“\nSum of Series up to %d terms : %f \n”,n,s);

}

Output:

Enter the number of terms: 6

1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6

Sum of Series up to 6 terms: 2.450000