C Program: Harmonic Series

The following series

$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + ...$

which is also represented as

$\Sigma_{n=1}^{\infty} \frac{1}{n}$

is known as a Harmonic Series.

oresme nicole Nicole Oresme. Public Domain

It was first shown by Nicole Oresme (AD c. 1320/25 – 1382), Bishop of Liseux, to be a divergent series.

The sum of the terms of the Harmonic Series upto a particular $n$ term is known as a partial sum.

Below we write a simple C program to find the partial sum of the Harmonic Series. We can achieve it using any of the while or do-while or for loops.

One important thing to note in the program code is, the variable i of type unsigned short is explicitly type casted to type float, for the resulting quotient is assigned to a variable of type float.

				
				#include <stdio.h>

				int main() {
					unsigned short int n, i;
					float sum = 0;

					printf("n: ");
					scanf("%hu", &n);

					for(i = 1; i <= n; i++) {
						sum += 1/(float) i;
					}

					printf("The sum of Harmonic Series upto %hu terms is: %f", n, sum);

					return 0;
				}