For Loops

A for loop is a special kind of a loop that compacts all of the pieces of the loop into one line.

This loop a little different than other loops because all pieces of the loop are not run at once. This is the order:

  1. Declare and initialise loop counter. This part happens once before the loop.
  2. Once at the start of every loop, the stopping condition is checked.
  3. The lines of code to be repeated are done once every time through the loop.
  4. The progression toward the stopping condition (i++) is done once at the end of every loop.

Here are some more examples of for loops and what each one prints out:

Loop Prints Out Start End Increase
for (int i = 0 ; i < 10 ; i++)
{
System.out.print (i + " ");
}
0 1 2 3 4 5 6 7 8 9 0 9 (<10) by 1
for (int i = 0 ; i < 10 ; i+=2)
{
    System.out.print (i + " ");
}
0 2 4 6 8 0 8 (<10) by 2
for (int i = 3 ; i < 10 ; i++)
{
     System.out.print (i + " ");
}
3 4 5 6 7 8 9 3 9 (<10) by 1
for (int i = 0 ; i <= 10 ; i++)
{
    System.out.print (i + " ");
}
0 1 2 3 4 5 6 7 8 9 10 0 10 (<=10) by 1