WAP to determine and print the sum of the following harmonic series for a given value of n: 1 + (1/2) + (1/3) + (1/4) + ... + (1/n)

The value of n should be given interactively through the terminal.

//E Balagurusamy, Programming In ANSI C,4E
//Exercise 2.1, page 51
#include <stdio.h>
#include <conio.h>
int main(void)
{int n=0, i=0;

float harmonic_sum=0.0;
printf("\n\n");
printf("===HARMONIC MEAN===\n");
printf("Enter the number of terms n : ");
scanf("%d",&n);
for (i=1; i<=n; i++)
    {harmonic_sum= harmonic_sum + (1.0/i);
    //observation: in "harmonic_sum= harmonic_sum + (1.0/i);"
    //if I put 1 instead of 1.0 in the last term, I get
    //1.000000
    //maybe because integer division
    //results in 0 for less than one numbers
    }
printf("Harmonic mean upto %d terms  : %f",n,harmonic_sum);
getch();
return 0;
}

Comments