Compute the sum of the harmonic series using a loop.
Algorithm implementation
Read the input value of .
scanf("%d", &n);Compute the sum of the harmonic series.
res = 0;
for (i = 1; i <= n; i++)
res = res + 1.0 / i;Print the answer.
printf("%.4lf\n", res);Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
double res = 0;
for(int i = 1; i <= n; i++)
res = res + 1.0 / i;
System.out.println(res);
con.close();
}
}Python implementation
Read the input value of .
n = int(input())Compute the sum of the harmonic series.
res = 0
for i in range(1,n+1):
res += 1 / iPrint the answer.
print(res)