[Solved] why does the for loop run twice only


Your loop is equivalent to this:

int i = 2;      // Initializer
while (i < 10)  // Condition
{
    System.out.println(i);
    i = i * i;  // Update part
}

Note how it will never enter the body of the loop when i is 10 or greater – so it will never print 16.

In other words, the execution looks like this:

  • Set i to 2.
  • Check: is i less than 10? Yes, so enter the body of the loop.
  • Print i.
  • Set i = i * i, so it’s now 4.
  • Check: is i less than 10? Yes, so enter the body of the loop.
  • Print i.
  • Set i = i * i, so it’s now 16.
  • Check: is i less than 10? No, so finish.

solved why does the for loop run twice only