TheLogicGuy
TheLogicGuy

Reputation: 690

Very basic function gives different answer with while loop and for loop

The first function with a while loop:

public static double sum(int n){
    double sum = 0;
    while (n!=0){
        sum+=1.00/((2*n-1)*(2*n+1));
        n--;
    }
    return sum;
}

The same function but with for loop gives another solution.

public static double sum1(int n){
    double sum = 0;
    for (int i=1;i<=n;i++){
        sum+=1.00/((2*n-1)*(2*n+1));
    }
    return sum;
}

The functions calculate the series:
1/(1*3) +...+ 1/((2n+1)*(2n-1))

For some reason the function with the for loop makes the sum smaller and smaller the while function works fine.
Why the for loop solution doesn't work?

Upvotes: 1

Views: 105

Answers (2)

Aaditya Gavandalkar
Aaditya Gavandalkar

Reputation: 824

You are not doing n-- in for loop and hence the difference.

You should change it to preferably:

public static double sum1(int n){ 
    double sum = 0; 
    for (int i=n;i>0;i--){ 
        sum+=1.00/((2*i-1)*(2*i+1)); 
    } 
    return sum; 
}

Upvotes: 0

Makoto
Makoto

Reputation: 106490

Your for loop is using the wrong variable - it should be using i instead.

In your while loop, you were using n as both the control and the value currently represented. You simply need to change your for loop to use i, since it represents the value you're currently iterating on.

Upvotes: 6

Related Questions