The nth harmonic number is defined nonrecursively as 1 12 1

The nth harmonic number is defined non-recursively as: 1 +1/2 + 1/3 + 1/4 + ... + 1/n. Come up with a recursive definition and use it to guide you to write a method definition for a double -valued  method  named  harmonic that accepts an int  parameters n and recursively calculates and returns the nth harmonic number.

Solution

HarmonicSeries.java

import java.util.Scanner;


public class HarmonicSeries {


   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print(\"Please enter the n value: \");
       int num = scan.nextInt();
       double result = harmonic(num);
       System.out.println(\"Harmonic Series Result: \"+result );

   }
   public static double harmonic (int n){
       if(n == 1) {
   return 1.0;
   } else {
   return (1.0 / n) + harmonic(n - 1);
   }
   }

}

Output:

Please enter the n value: 8
Harmonic Series Result: 2.7178571428571425

The nth harmonic number is defined non-recursively as: 1 +1/2 + 1/3 + 1/4 + ... + 1/n. Come up with a recursive definition and use it to guide you to write a me

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site