Interation Structures (Loops)

In order to repeat an instruction or piece of code a loop has to be used.

There are two main different types of loops, non-conditional and conditional loops. A non-conditional loop is a loop that is set to run a fixed number of times before the program is actually run. An example of such a loop is the for loop.

A conditional loop is a loop which checks a condition each time it runs. This means that it can decide whether it must still run based on condition or logical comparison. Examples of this kind of loop are the while and do..while loops.

For loop 

A for loop uses a loop variable to keep track of how many times it must run. This must be an int variable and is declared and used in the first part of the round brackets placed after the for keyword.
The second part of the loop, separated by a semi-colon, is used to say until what point the loop must run. In our example below the loop checks each time that i is still less than 10. If i is 10 then the loop will no longer run.

The following example prints out to screen the numbers 1 – 10:

for (int i = 0; i < 10; i++)
{
    System.out.println(i); // print to screen the loop variable i
}

while loop

A while loop is a conditional loop that will continue to repeat until its condition is no longer valid.
The while statement tests the condition at the beginning of the loop, before any code is executed inside the loop. For this reason it is called a pre-condition test loop.

while (gamesLives > 0)
{
    System.out.println("continuing the game.");
}

This loop will continue repeating until the gameLives variable is no longer greater than 0.

do-while loop

A do-while loop is similar to the whilte loop but the loop’s condition is only tested AFTER the loop has run once. Just like the while loop, the loop while continue looping until the condition is false but the check is done after the code inside the loop is executed instead of before.

do
{
    System.out.println("This will run at least once.");
} while (gameLives > 0);

The code inside the loop will be execute at least once and will continue to loop while thegameLives variable is greater than 0.
Note the semi-colon after the condition.