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
- Use double for the sum to handle decimals
- Divide 1.0 by i (not 1/i which gives 0)
- Use String.format("%.4f", sum) for formatting
Related Control Flow exercises
- Practice Nth Fibonacci Number in Java
- Practice Print Primes in Range in Java
- Practice Number Pattern in Java
Practice all Control Flow exercises · Run this idea in the Java compiler