Sum of Series in Java: Explanation & Practice

Calculate 1 + 1/2 + 1/3 + ... + 1/n

Problem summary

Write a program that calculates the sum of the series 1 + 1/2 + 1/3 + ... + 1/n.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 5; // Test case 1
        
        // Calculate sum: 1 + 1/2 + 1/3 + ... + 1/n
        // Print with 4 decimal places: Sum: <result>
    }
}

Expected output and test cases

  • 1+1/2+1/3+1/4+1/5
    Sum: 2.2833
  • 1+1/2+1/3+1/4
    Sum: 2.0833
  • 1
    Sum: 1.0000

Hints

  1. Use double for the sum to handle decimals
  2. Divide 1.0 by i (not 1/i which gives 0)
  3. Use String.format("%.4f", sum) for formatting

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler