Practical-7
Write a Java Program that will display the Sum of 1+1/2+1/3…..+1/n.
Introduction
This program will use Java to calculate and display the sum of 1+1/2+1/3+.....+1/n. It will use a for-loop to calculate 1/i and then add it to the total sum. The starting point of the loop is 1, and the value of n (number of terms in the sequence) will be provided by the user.
Code
// Take the number of terms in the sequence from user
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the number of terms in the sequence: ");
int n = scanner.nextInt();
// Variable sum to store the total sum of the sequence
float sum = 0;
// For-loop to calculate 1/i
for (int i=1; i<=n; i++) {
sum = sum + 1.0f/i;
}
// Print the sum
System.out.println("The sum of the series is : "+sum);
Output
Please enter the number of terms in the sequence:
10
The sum of the series is : 2.8289683
Explanation
The code begins by asking the user for the number of terms in the sequence. This number is saved in the variable n. We then initialize a variable sum to 0, which will store the total sum of the sequence. In the for-loop, we start with i = 1, and each value of i from 1 to n is added to sum one by one. Finally, we print out the value of sum.