by BehindJava
WAP to print the sum of harmonic progression series
In this tutorial we are going learn about printing the sum of harmonic progression series.
Let’s take the user input n with the scanner(system.in) and pass it on to a method as an argument and using a for loop we will run the loop till n and returns the sum of the series.
Note: Harmonic progression can be denoted as 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) …. 1/(a + nd).
Sample input:
n=5
Output:
2.283333
Sample Code Snippet:
public class HarmonicProgression {
public double printHpSum(int n)
{
double sum=0.0,i;
for(i=1;i<=n;i++)
{
sum=sum+1/i;
}
return sum;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HarmonicProgression hp=new HarmonicProgression();
System.out.println(hp.printHpSum(n));
}
}
Output:
8
2.7178571428571425