harmonic1.c

This program computes partial sum of harmonic series
       1 + 1/2 + 1/3 + ... +1/N

and displays the intermediate partial sums. The heart of the program is the for loop. As the control variable i runs from 1 to N, the partial results are accumulated in the variable sum . Executing the construct LHS += RHS adds RHS to LHS. In our program we could have said sum = sum + 1.0/i instead of sum += 1.0/i. The latter often results in faster code, however.

#include <stdio.h>
#define N 20

main()
{
  int i; float sum = 0;
  
  for (i=1; i <= N; i++){
    sum += 1.0/i;
    printf("%d:  %4.6f\n", i, sum);
  }
}