Reputation: 141
I have a problem. I am trying to use a for loop to run a PI approximation. The following is my code (From after main). Why does this loop never terminate?
System.out.println("Start");
double sum1 = 1.0, sum2 = 1.0;
int j =1;
for(int i=1;i<6;i++)
{
if((j/2)!=0)
i = i*-1;
if(i>5)
{
sum1 += 0;
}
else
{
sum1 += ((double)1.0/(i+2.0));
sum2 += ((double)1.0/(i+2.0));
}
j++;
}
System.out.println("PI 1 = " + 4*sum1);
System.out.println("PI 2 = " + 4*sum2);
Upvotes: 0
Views: 64
Reputation: 9770
Because you modify i
inside of your loop to be negative when j
is greater than or equal to 2, you can't guarantee the loop terminates.
In fact, i
continuously oscillates between a positive and negative number on successive iterations after j >= 2
.
Upvotes: 2