I'm supposed to recreate this code
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
x = x+-(1.0/i);
}
System.out.print(+x);
}
But with alternating signs in the loop (1 – 1/2 + 1/3 – 1/4 + 1/5 – 1/6 + ... + 1/N) and have it print out the value (Enter an integer: 5 The total is: 0.7833333333333332)
I was wondering how I could do this? I was able to write the original code, but I am unaware as to how I could replicate the code but with alternating signs.
This may be what you are trying to do. The important change is the
if(i%2==0)logic - Here I use it as a way of alternating on the different iterations of the for loop based on whetheriis even or odd.Hope this helps, feel free to ask any questions