Iteration

These ants are trying get to the end of this loop. They may have to do so for a while…

One of the things that makes computer programs so useful is their ability to repeat sections of code over and over again. This is formally called iteration, but programmers will almost always refer to such sections of code as loops. Think of an aircraft flying in an acrobatic display, it dives down and then rolls back up turning upside down and flies back down again to complete a circular loop. Think also of the loop in a typical roller coaster.

Most high level programming languages offer three different styles of loop, each of which might be useful in one particular situation.

for loop

The for loop is a structure that runs a block of code for a fixed number of times. The general syntax in Java and other C style languages is:

for (initialisation; termination; increment) {
    line1
    line2
    etc
}

The lines enclosed between the open and close curly brackets make up the block of code that will repeat. A count variable is used to keep track of the number of times we have repeated, and the content of this variable changes each time round the loop automatically. We can give the variable a name and initial value in the initialisation part of the statement. A termination condition is used to decide when the loop should stop. The increment part of the statement is used to decide how much we should increase (or decrease) the count variable.

For example the code below prints the numbers 0 to 20 inclusive so it will run 21 times in total.

int i;

// start i at zero, repeat while i is less than 21
for(i=0; i<21; i++){
    System.out.println(i); // print the value of i
}

while loop

A while loop executes a block of code only if the test condition at the beginning of the loop is true. It will therefore possibly never execute the code inside the block.

while (condition) {
    line1
    line2
    etc
}

The condition, which you can think of as a question being asked, is placed in the round brackets. If the condition evaluates to true, the code inside the block marked by curly brackets runs. If false it will not run the code inside the curly brackets, and will carry on to whatever the next line is after the closing curly bracket. The difference between the while and the if structures is that the the block of code keeps on repeating while the condition is true (hence the name).

Scanner keyboard = new Scanner (Sytem.in);

// hasNext() returns true if there is still input
while ( keyboard.hasNext() ) {		
    s=keyboard.next();
    System.out.println(s); 
}

do loop

A do loop executes a block of code whilst the test condition at the end of the loop is true. It will therefore always execute the code in the block at least once.

do {
    line1   
    line2
    etc
} while (condition);

Like the while loop, the curly brackets mark the start and end of the block of code that will repeat. The round brackets contain a condition, which evaluates to true or false. The block of code will keep on repeating until the condition becomes false. Therefore, in some languages this is called a repeat…until loop.

Note this is one of the only times in a Java program where you will see a semi colon and a closing curly bracket on the same line.

int tries=0;
do {
    guessLetter();
    displayHangMan(tries);   	
    tries++;
} while (tries<10);

if(tries!=10){
System.out.println("You did it in "+tries+" tries");
}

Nested loops

A loop contained within another is known as a nested loop. The first loop is know as the outer loop, and the loop within it is known as the inner loop. It is perfectly okay to mix different types of loop, i.e. you could have a while loop inside a for loop, as in the example below.

int i,j;

for (i=0; i < 10; i++){
    System.out.println(i);
    j=0;
    while ( j < 10 ){//these lines will run 100 times each
        System.out.print(j); 
        System.out.print(" ");
        j=j+1;
    } // end of inner loop
    System.out.println(j);
} // end of outer loop

Practice exercises

  1. Create a program that uses a for loop to print out the numbers 0 to 10 backwards.
  2. Create a program that displays all the times tables from 1 to 12.
  3. Create a program that repeatedly takes an integer number from the user via the keyboard. The program should keep track of the highest number entered so far, and the lowest number entered so far. When the user enters -1, the program ends and displays the highest and lowest numbers entered.
  4. In mathematics, the Fibonacci numbers are the numbers in the following integer sequence:

0,1,1,2,3,5,8,13,21,34,55,89,144…

They are calculated by summing the previous two numbers, starting with the integers 0 and 1. Write a program that asks for input n, and then calculates n numbers in the Fibonacci sequence. In the above example n would be 13

Knowledge check

  • What is the purpose of a loop?
  • Why are there three different types of loop?
  • What is the difference between a while loop and a do loop?
  • What is another name for a do loop in some other languages?