for ( init ; cond ; update ) for bodywhere
A single statement is now extended to mean:
for ( init ; cond ; update ) for bodyThe semantics of how to run this loop are:
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.
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.
Fifth, the common problem is not jumping to the loop body after the condition evaluates to true.
Here's a short example:
int i = 0 ; for ( ; i < num ; i++ ) // init is blank { // CODE }
`
Here's a short example:
for ( int i = 0 ; i < num ; ) // update is blank { // CODE }
Normally this causes an infinite loop, which sounds just as bad (because it never leaves the loop). However, there are control flow constructs which allow us to escape the loop.