The 1+1/2+1/3+...+1/n Sum Formula in C
The harmonic series is a well-known mathematical concept that has been studied for centuries. The sum of the reciprocals of the positive integers, also known as the harmonic series, is a divergent infinite series. However, we can calculate the sum of the first n
terms of the harmonic series, which is a convergent series.
The Formula
The sum of the first n
terms of the harmonic series is given by the formula:
$1 + \frac{1}{2} + \frac{1}{3} + ... + \frac{1}{n} = \sum_{k=1}^{n} \frac{1}{k}$
Implementation in C
Here is an example implementation of the formula in C:
#include
double harmonic_sum(int n) {
double sum = 0.0;
for (int k = 1; k <= n; k++) {
sum += 1.0 / k;
}
return sum;
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
double sum = harmonic_sum(n);
printf("The sum of the first %d terms is: %f\n", n, sum);
return 0;
}
Explanation
The harmonic_sum
function takes an integer n
as input and returns the sum of the first n
terms of the harmonic series. The function uses a for
loop to iterate from 1
to n
, adding the reciprocal of each term to the sum.
In the main
function, we prompt the user to enter the number of terms n
, and then call the harmonic_sum
function to calculate the sum. Finally, we print the result to the console.
Example Output
Here is an example output of the program:
Enter the number of terms: 5
The sum of the first 5 terms is: 2.283333
Note that the actual output may vary depending on the value of n
entered by the user.
I hope this helps! Let me know if you have any questions.