Incremental Java
for

Syntax

Here's how a for loop looks
for ( init ; cond ; update )
  for body 
where As usual, the for body must either be a block or a single statement.

A single statement is now extended to mean:

Semantics

The for loop is the most complex of the loops we've seen, but once you get used to it, it should be easy to follow.
for ( init ; cond ; update )
  for body 
The semantics of how to run this loop are:
  1. ENTER the for loop (so far, no code is run)
  2. Run init
  3. Evaluate cond
  4. If cond evaluates to true, run for body and go to step 3.
  5. If cond evaluates to false, EXIT the for loop.
You may wonder why we have an ENTER and EXIT. This is important once we talk about nested for loops. In particular, it tells you when to run init.

Common Problem

Let's trace through a typical for loop.
for ( int i = 0 ; i < num ; i++ )
{
   System.out.println( i ) ;
}
To do this trace, I want to rewrite the code so I can refer to it more easily. It's just a matter of reindenting.
for ( int i = 0 ;     // LINE 1
      i < num ;    // LINE 2
      i++ )           // LINE 3
{
   System.out.println( i ) ; // LINE 4
}
Let's assume num is 2. Several notes. First i is a very common choice for a looping variable. It's not descriptive, but so many programmers use it. j is often used too, though i is more common.

These choices come from FORTRAN. In that language, variables starting from about i to n were considered integer variables (you didn't have to declare the types---the FORTRAN compiler assumed the type based on the first letter of the variable name).

Second, once the condition is evaluated, you jump to the loop body. The update is done afterwards.

Third, we declared i in init. This variable only has scope within the loop. After you exit the loop, i is no longer valid. It becomes valid again, once you re-enter the loop.

Fourth, the kind of loop you see above is perhaps the most common form of the for loop.

It runs num iterations.

Fifth, the common problem is not jumping to the loop body after the condition evaluates to true.

Practice Makes Perfect

Try tracing the loop where num is 5.

Leaving Parts Blank

In a while loop and a do while loop, you must have a condition. However, in a for loop, any of the three fields can be left blank.