Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads in a target and finds the first n such that 1 + 1/2 +

ID: 3857456 • Letter: W

Question

Write a program that reads in a target and finds the first n such that 1 + 1/2 + 1/3 + ... + 1/n > target.

Please provide an explanation for why you choose to initialize each variable and why do choose to write the statement.

import java.util.Scanner;

/**
This program computes how many steps the sum 1 + 1/2 + 1/3 + ...
needs to exceed a given target.
*/
public class ReciprocalSum
{
public static void main(String[] args)
{
  
double sum = . . .;
int n = . . .;

Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();

while (. . .)
{
. . .
sum = . . .;
}
  
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}

Explanation / Answer

Hi,

Please find below the updated code and the explanation for each initialization inline.

import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
  
double sum = 0;//This variable is to store the sum of series. We need to use it inside the loop using java shothands. Hence, it is necessary to initialize it with some initial value.
int n = 2;// This variable is used to act as a denominator of the series. As the series starts with 1/2, we need to initialize it with2 and then we can increment this variable inside loop.
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
while (sum<=target)
{
sum +=1+1/n ;
n=n+1;
}
  
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote