aqibjr1
aqibjr1

Reputation: 594

Confusion about counter variable at loop termination

For this snippet of code:

int number = 25;
int i;

boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
  if (number % i == 0) {
    isPrime = false;
  }
}

System.out.println("i is " + i + " isPrime is " + isPrime);

I was under the impression that the output would be: "i is 5 isPrime is false", since when i=5, number % i == 0 is true, thus the variable isPrime becomes false and the loop won't continue.

So when the loop returns to

for (i = 2; i < number && isPrime; i++)

it wouldn't increment i, since the condition is no longer valid (i < number && isPrime). What's going on?

Upvotes: 0

Views: 223

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477328

I think you understand the concept of a loop the wrong way. A for loop with the structure:

for(init; cond; inc) {
    body
}

works as follows:

  1. First the init is executed;
  2. Next the condition is evaluated, if the condition is true, goto 3, otherwise, end loop.
  3. The body is executed
  4. The inc is executed (regardless whether the condition holds);
  5. goto 2.

As is specified, the increment (for your example i++ will always be called after executing the body, regardless whether the condition holds. You could therefore rewrite the above for loop as:

for(init; cond;) {
    body;
    inc
}

(so with an empty increment at the for header). Here a compiler has no means to disambiguate between body and inc. The syntax of the for loop is structured that way such that programmers would not forget to perform an increment, a typical error that occurs often with while loops.

Upvotes: 7

Jules
Jules

Reputation: 587

I've never seen someone writing for-loops like this. Try it by using the break keyword instead:

int number = 25;
boolean isPrime = true;

for (int i = 2; i < number; i++) {
    if (number % i == 0) {
      isPrime = false;
      break;
  }
}

System.out.println("i is " + i + " isPrime is " + isPrime);

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533750

If you loop was to stop on i < number it would have to i++ first.

The loop doesn't know that you will be stopping on isPrime instead and "know" to not bother incrementing.

What you should do is drop the flag as it would be simpler.

int number = 25;

for (int i = 2; i < number; i++) {
  if (number % i == 0) {
     System.out.println("i is " + i + " " + number + " is not prime");
     break;
  }
}

Upvotes: 3

Related Questions