Alternating signs + loops

1.1k Views Asked by At

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.

3

There are 3 best solutions below

0
NBlaine On
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++){
            if(i%2==0){ //even
                x = x-(1.0/i);
            }
            else{ //odd
                x = x+(1.0/i);
            }
        }
        System.out.print(+x);
    }

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 whether i is even or odd.

Hope this helps, feel free to ask any questions

0
user31601 On

Change x = x+-(1.0/i); to x -= Math.pow(-1,i)/i;. That should do the trick.

0
Joop Eggen On
    double s = -1; // Sign factor
    for (int i = 1; i <= n; i++) {
        s = -s;
        x += s/i;
    }