Java Program to Generate Harmonic Progression(HP) Series

In this java program, we have to generate harmonic series and print the sum of harmonic series till N terms.

Harmonic Progression Series
Harmonic series is a sequence of terms formed by taking the reciprocals of an arithmetic progression.
Let A, A+D, A+2D, A+3D .... A+nD be Arithmetic progression series till N+1 terms with A and D as first term and common difference respectively. Then corresponding Harmonic series will be
1/A, 1/(A+D), 1/(A+2D), 1/(A+3D) .... 1/(A+nD).

Java Program to generate Harmonic Series and find it's sum till N terms

To generate a harmonic series, we first ask user to enter the number of terms in harmonic series. Using a for loop, we generate and print the harmonic series till N terms and at the same time calculate the sum series elements.

package com.tcc.java.programs;

import java.util.Scanner;

class HarmonicSeries {
    public static void main(String args[]) {
        int terms, i;
        double sum = 0.0;

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of terms in series");
        terms = scanner.nextInt();
        System.out.println("Harmonic Series");
        // Printing harmonic series
        for (i = 1; i <= terms; i++) {
            System.out.print("1/" + i + " ");
            sum += (double) 1 / i;
        }

        System.out.format("\nSum of Harmonic Series is %f", sum);
    }
}
Output
Enter the number of terms in series
7
Harmonic Series
1/1 1/2 1/3 1/4 1/5 1/6 1/7 
Sum of Harmonic Series is 2.592857