Print the sum of nth harmonic number: 1/1 + 1/2 + … + 1/n.
Note: Use Double Data type and String.format(“%.02f”, variable name)
Input:
5 // nth number
Output:
2.28 // sum of nth harmonic number
import java.io.*; import java.util.*; public class temp{ public static void main(String[] args){ int n; Scanner scan = new Scanner(System.in); System.out.print("Enter nth number: "); n = scan.nextInt(); double s=0; for(int i=1;i<=n;i++) { s+=(float)1/i; } System.out.println("Sum = "+String.format("%.02f",s)); } }
INPUT_1:
Enter nth number: 5
OUTPUT:
Sum = 2.28
INPUT_2:
Enter nth number: 10
OUTPUT:
Sum = 2.93
INPUT_3:
Enter nth number: 20
OUTPUT:
Sum = 3.60
INPUT_4:
Enter nth number: 8
OUTPUT:
Sum = 2.72
INPUT_5:
Enter nth number: 56
OUTPUT:
Sum = 4.61
INPUT_6:
Enter nth number: 100
OUTPUT:
Sum = 5.19
ILLUSTRATION