Java Program to Generate Harmonic Series

This is a Java Program to Generate Harmonic Series.

We take a number as an input and using loops we generate the Harmonic series and get the desired output.

Here is the source code of the Java Program to Generate Harmonic Series. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. class Harmonic
  3. {
  4. public static void main(String... a)
  5.     {
  6.         System.out.print("Enter any number : ");
  7.         Scanner s = new Scanner(System.in);
  8.         int num = s.nextInt();
  9.         System.out.print("The Harmonic Series is : ");
  10.         double result = 0.0;
  11.         while(num > 0)
  12.           {
  13.                result = result + (double) 1 / num;
  14.                num--;
  15.                System.out.print(result +"  ");
  16.           }
  17.         System.out.println("");
  18.         System.out.println("Output of Harmonic Series is "+result);
  19.     }
  20. }

Output:

$ javac Harmonic.java
$ java Harmonic
 
Enter any number : 5
The Harmonic Series is : 0.2  0.45  0.7833333333333333  1.2833333333333332  2.283333333333333  
Output of Harmonic Series is 2.283333333333333

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.