The harmonic series adds the first n elements of the series

The harmonic series adds the first n elements of the series 1+1/2+1/3 +1/4 +1/5+ +1/n. Write a recursive algorithm to calculate the harmonic series for a given vale n. (in java) Using the following format for an algorithm Function header Input: Output: Algorithm steps: 1. 2.

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

 The harmonic series adds the first n elements of the series 1+1/2+1/3 +1/4 +1/5+ +1/n. Write a recursive algorithm to calculate the harmonic series for a given

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site