Sum of Harmonic series for a given value of N

By | August 5, 2017

As the name suggests, the harmonic series is the divergent infinite series:

This program is to find the sum of harmonic series to Nth element 1+1/2+1/3+..1/n.

Its a basic and simple program with a for loop.

Examples:

Input: 5
Output: 2.2833335

Input: 10
Output: 2.9289684

Solution

import java.util.Scanner;
public class Harmonic {
    public static void main(String[] args) {
        float sum = 0;
        float i = 0;
        // Scanner is used to take the input from the user 
        Scanner scanner = new Scanner(System.in); 
        System.out.println("Enter The Value N Element"); 
        int n = scanner.nextInt();
        for (i = 1; i <=n; i++)
        {
            sum = sum + 1 / i;           // we are putting the logic here
        }
        // this will show the output
        System.out.println("Sum will be:" + sum);
    }
}

Output

Enter The Value N Element 5
Sum will be: 2.2833335