The harmonic series adds the first n elements of the series
Solution
SumOfHarmonicSeries.java
import java.util.Scanner;
public class SumOfHarmonicSeries {
public static void main(String[] args) {
//Declaring variables
int n;
double sum;
//Scanner class object is used to read the inputs entered by the user
Scanner sc=new Scanner(System.in);
//Getting how many terms in the harmonic series user want to add
System.out.print(\"How many elements you want to add :\");
n=sc.nextInt();
//Calling the method by passing the no of terms
sum=addHarmonicSeries(n);
//Displaying the Sum of no of terms in harmonic series
System.out.printf(\"The sum of %d terms in Harmonic Series is : %.2f\",n,sum);
}
/* This function will add the number of terms in harmonic series
* Params: no of terms of type int
* return : sum of terms of type double
*/
private static double addHarmonicSeries(int n) {
//If the no of terms is 1 then return 1
if(n==1.0)
return 1.0;
else
//Recursively add the number of terms in harmonic series
return (1.0/n)+(addHarmonicSeries(n-1));
}
}
_________________________________
input:
How many elements you want to add :5
output:
The sum of 5 terms in Harmonic Series is : 2.28
______________Thank You
