Introduction
In this post, we’ll learn how to write a C program to calculate the harmonic series:
1 + 1/2 + 1/3 + 1/4 + … + 1/n
The harmonic series is commonly used in mathematics, data science, and algorithm analysis. Calculating it programmatically helps reinforce loop constructs and floating-point arithmetic in C.
Problem Statement
Given a positive integer n
, compute the sum of the harmonic series up to n
terms.
For example, if n = 5
, the series is:
1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.2833
C Program to Find Harmonic Series Sum
#include <stdio.h>
int main() {
int n, i;
float sum = 0.0;
printf("Enter the value of n: ");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("Sum of the harmonic series up to %d terms is: %.4f\n", n, sum);
return 0;
}
Explanation
- Input: User enters the number
n
- Loop: Runs from 1 to
n
and adds the reciprocal of each number tosum
- Precision:
1.0 / i
ensures the division is done in float, not integer - Output: The result is shown up to 4 decimal places using
%.4f
Example Output
Enter the value of n: 5
Sum of the harmonic series up to 5 terms is: 2.2833
Why This is Important
The harmonic series is widely used in:
- Time complexity of algorithms (like the Harmonic Mean)
- Network load calculations
- Theoretical mathematics and number theory
- Scientific simulations involving inverse relationships
Conclusion
This C program harmonic series example helps beginners understand loops and floating-point calculations. It’s also a useful exercise in mathematical modeling using C programming.