How does the for loop exactly work out [closed]

Solution 1:

A for loop works as follows:

  1. Initialization is done (int i=0 in your case; only executed once)
  2. Condition is checked (i<=100 here), if condition is false leave the loop
  3. Code within the braces is executed (System.out.println(i); in your case)
  4. Update statement is executed (i++)
  5. Goto 2.

Solution 2:

It's similar to this while loop :

{
    int i = 0;
    while (i <= 100) {
        System.out.println(i);
        i++;
    }
}

i is incremented only at the end of each iteration.

Solution 3:

Because the increment is evaluated after the first execution of the loop body. This is by design, and remember that programmers generally treat 0 as the first number. For example, with arrays and String(s) the first element is 0.

The Java Tutorial on The for Statement says,

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) {
  statement(s)
}

When using this version of the for statement, keep in mind that:

The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.