Introducing Iteration

All of the methodss you have seen so far are executed in exactly the order they are written: starting with the first line, moving through each of the lines in turn until it reaches the last line, then ending. This does not lead to very flexible programs. What if we wanted to, for example, repeat the same set of instructions more than once? We could obviously write the instructions out as many times as necessary, or place them in a function and call this where necessary. Unfortunately this does not cope with the situation where the number of repetitions is determined by a number entered from the keyboard. We might also want our program to perform different actions in response to the input it receives. Neither of these scenarios can be handled adequately by simple sequential execution of instructions.

This set of exercises will introduce the first of two extremely important programming concepts, iteration (or repetition) and selection (or making decisions). Iteration and selection are important because they allow a programmer to modify a program's flow of control, that is, the order in which the instructions are executed. Calling functions also changes the flow of control, but without iteration and selection functions are really just 'syntactic sugar'; they save some space and perhaps make the program easier to read but otherwise do not change its operation at all.

Solutions to the exercises are available here.

The code for these notes can be found in the directory:

/import/teaching/BSc/1st/ItP/forloops

The for loop

Java offers three different iteration statements: for, while and do. These are often referred to as loop statements, because they cause the program to repeatedly execute a sequence of instructions, 'looping back' to some earlier point in the code between each execution. The instructions executed 'inside' the loop are known as the loop body. The number of repetitions made by a loop is determined by a conditional expression: an expression that evaluates to one of the values true or false. Some examples of conditional expressions are:

x == 6
(is x equal to 6?)
x < 21
(is x less than 21?)
x >= 45
(is x greater than or equal to 45?)
x != 0
(is x not equal to zero?)

More complicated conditional expressions are of course possible. The important point to realise is that each of these expressions evaluates not to a numeric value but to a yes/no or true/false answer. Note also that the symbol for test equality is == whereas the symbol for assignment is just =. One of the commonest mistakes made even by experienced programmers is to mix up these two symbols -- fortunately the Java compiler will usually let you know when you have used the wrong one.

The most interesting of the iteration statements is the for statement, shown in Prog31 below and available in the file /import/teaching/BSc/1st/ItP/Prog31.java. See if you can predict how this program will behave before you run it.

1  class Prog31 {
2
3    // A program demonstrating the use of a 'for' loop
4    public static void main(String[] args) {
5      int i;
6
7      for (i = 0; i < 10; i = i + 1) {
8        System.out.println("i = " + i);
9      }
10     System.out.println("Final value of i: " + i);
11   }
12 }
    

The only unfamiliar part of this program should be the for statement on line 7. This statement is the most general iteration construct offered by Java. A for loop repeats the loop body as long as the specified conditional expression remains true and gives the programmer complete control over the actions carried out between each iteration. The statement itself consists of four parts, as shown below: the initialisation, condition, update and body. We will examine each of these parts individually.

for (< initialisation >; < condition >; < update >) {
  < body >
}
    

Initialisation

The first part of the loop statement allows you to initialise the variable or variables that will be used to keep track of how many times the loop body has been executed, and whether it is time to terminate the loop yet. Any initialisation expression that can be used in a variable declaration can also be used in the initialisation part of a for loop. Multiple variables may be initialised by separating the expressions with a comma. The following examples show some of the possibilities:

for (i = 0; ... ) { ... }
    
for (i = 0, j = 0; ... ) { ... }
    
for (long x = 15, y = x; ... ) { ... }
    
for (int i = square(4); ... ) { ... }
    

As you can see, it is even possible to declare new variables within the initialisation section. Note that any variables declared in this way can only be used within the header and body of the loop. This effect is caused by Java's rules of variable scope, which will be discussed in greater detail later in the course.

The example for loop in Prog31 initialises the integer variable i to zero. This variable will be used to count the number of times the body of the loop has been executed.

Condition

The second part of the loop header consists of a single conditional expression. The value of this expression is used to decide whether the body of the loop should be executed or the loop should be terminated. The expression is evaluated before the loop body is executed for the first time and again after each execution of the body. If the value of the expression is false, the loop will be terminated and the program will continue from the statement immediately following the loop body. Note that it is possible to write a condition such that the loop body will not be executed at all, if the condition evaluates to false the very first time it is tested.

In our example for loop, the condition part checks that the value of i is less than 10. Since we initialised i to be zero in the initialisation part, the loop body will be executed at least once (because zero is less than 10).

Update

The final part of the loop header is used to update variables after the loop body has been executed. The format of the update part is exactly the same as the initialisation part, except that new variables may not be declared here. The difference is that the update expressions are evaluated immediately after each execution of the loop body, before the condition is tested. Usually, but not always, the update expressions will update variables that were initialised by the initialisation part and are about to be tested by the condition part. Some examples of typical for loop update expressions are shown below:

for ( ...; i = i + 1 ) { ... }
    
for ( ...; i = i + 1, j = j - 3) { ... }
    
for ( ...; x = square(y)) { ... }
    

The update part of the example loop in Prog31 simply adds 1 to the value of i.

Body

The final part of the for loop to be considered is the body. This consists of a single statement, or a sequence of statements enclosed in brackets ('{' and '}'). The body is executed immediately after each time that the condition is evaluated (provided that the condition evaluates to true), and immediately before each time that the update expressions are evaluated. The code within the body is completely arbitrary: it can include other loops, function and method calls, and modify the variables used in the loop header.

The body of our example loop prints out the current value of i each time it is executed.

Detailed analysis of the example

Now that you know how a for loop is put together, we will work through the execution of the loop in Prog31 in more detail. First of all, the loop initialisation sets i to zero. Then, the condition is evaluated and, since it evaluates to true, the loop body is executed. The text i = 0 will be printed on the screen. After the body has executed, the update expression is evaluated and the value of i is increased to 1. The first iteration of the loop is then complete.

To decide whether or not there will be a second iteration of the loop, the condition is evaluated again. As it still evaluates to true (since 1 is still less than 10), the body of the loop will be executed a second time. This time, the text i = 1 will be printed. The evaluation of the update expression will increase the value of i to 2.

Things continue in this fashion until the tenth iteration of the loop. By this time, the value of i has increased to 9. This is less than 10, so the loop body will be executed for the tenth time and the text i = 9 printed on the screen. The update expression then increases the value of i to 10. When the condition expression is evaluated again (to decide if there will be an eleventh iteration of the loop), it evaluates to false, since 10 is definitely not less than 10! This is the signal to terminate the loop, so the body will not be executed again and the program will continue from the line immediately after the body. This line prints out the text Final value of i: 10 before the program ends.

More example for loops

Programs Prog32, Prog33 and Prog34 (all available from the usual directory) are further examples of typical for loops. You should attempt to work through these programs by hand and predict their behaviour before compiling and running them. Make sure you understand the operation of these program thoroughly before you try the exercises below!

1  class Prog32 {
2
3    // Another 'for' loop demonstration
4    public static void main(String[] args) {
5      int i;
6  
7      for (i = 10; i > 0; i = i - 1) {
8        System.out.println("i = " + i);
9      }
10     System.out.println("Final value of i: " + i);
11   }
12 }
    
1  class Prog33 {
2  
3    // Another 'for' loop demonstration
4    public static void main(String[] args) {
5      int i;
6  
7      for (i = 10; i >= 0; i = i - 2) {
8        System.out.println("i = " + i);
9      }
10     System.out.println("Final value of i: " + i);
11   }
12 }
    
1  class Prog34 {
2  
3    // Another 'for' loop demonstration
4    public static void main(String[] args) {
5      int i;
6  
7      for (i = 1; i < 100; i = i * 2) {
8        System.out.println("i = " + i);
9      }
10     System.out.println("Final value of i: " + i);
11   }
12 }
    

Exercises

  1. Write a program containing a for loop that will print out the following values, one per iteration of the loop: -10, -7, -4, -1, 2, 5, 8.

  2. As above, but print the values: 3, 6, 9, 12, 15, 18, 21.

  3. As above, but print the values: 128, 64, 32, 16, 8, 4, 2, 1.

  4. As above, but print the values: 1, 1, 2, 3, 5, 8, 13, 21. (Hint: this one is harder! You will probably need to use two extra variables in the loop)

  5. Write a program which reads an integer from the keyboard (call it x), the prints the sequence 0, 1, 2, ..., x, x+1, x+2, ..., 2x. If the original x is less than zero, nothing should be printed.

  6. How many times is the loop body 'X' executed in each of the following for loops? You could write programs to answer these questions, but you will probably learn more working out the answers by hand.

    1. for (int i = 0; i < 16; i = i + 1) {
         X
      }
      	    
    2. for (int i = 0; i <= 16; i = i + 1) {
         X
      }
      	    
    3. for (int i = 27; i > 14; i = i - 2) {
         X
      }
      	    
    4. for (float f = 3.1F; f <= 10; f = f + 0.25F) {
         X
      }
      	    
    5. for (int i = 1, j = 3; j < 100; i = i * 2, j = j + i) {
         X
      }
      	    
    6. for (int i = 0; i < 101; i = i + 1) {
         i = i + 1;
      }
      	    

More fun with for loops

As I have mentioned a couple of times already, the for loop is the most versatile of the iteration constructs offered by Java. In fact, anything that can be done with a while or do loop can also be done with a for loop, although generally not as elegantly. So why have three different loop statements? The while and do constructs correspond to particular styles of iteration that occur frequently and can be more cleanly expressed with their own statement rather than a complicated for loop. Additionally, having the different statements makes it easier for a person to follow the logic of the program: it is easy to spot a while loop on the code but much harder to determine if a particular for statement is really a while loop in disguise!

Before moving on to cover while and do loops, this section will present a few more interesting variations on the basic for loop.

Any (or all) of the three 'header' section of the for statement can be left empty. Why would you want to do this? If the variables to be used in the loop are already set to appropriate values, it is not necessary to do any initialisation in the loop header itself. Similarly, if the loop body performs any necessary updates to the loop variables, it is not necessary to include any update expression in the header. This approach is often used when the initialisation/update expressions are especially complex or there are a lot of variables to be updated/initialised. For instance, the following two programs are equivalent:

1  class Prog35a {
2
3    // A program to calculate the factorial of 11
4    public static void main(String[] args) {
5      int i, j, k;
6
7      for (i = 1, j = i, k = 11; i <= k; i = i + 1, j = j * i) {
8        System.out.println(j);
9      }
10   }
11 }
    
1  class Prog35b {
2
3    // A program to calculate the factorial of 11
4    public static void main(String[] args) {
5      int i, j, k;
6
7      i = 1;
8      j = 1;
9      k = 11;
10     for ( ; i <= k; ) {
11       System.out.println(j);
12       i = i + 1;
13       j = j * i;
14     }
15   }
16 }
    

Note that in the second example the semicolons are still included in the loop header, even though the initialisation and update sections are empty. It is debatable which of the two programs is easier to read and understand and in practice a compromise solution would probably be used: i, which is just used as a counter, would remain in the loop header, while the rest of the calculation would be carried out in the body of the loop.

It is also possible to leave the condition section of the loop header empty. What should the value of an empty conditional expression be? As it happens, Java effectively evaluates an empty conditional expression to always be true, meaning that a for loop containing such a condition will never terminate (because the condition never becomes false). Such a loop is known as an infinite loop or, in the specific case of an infinite for loop, a forever loop. The uses of infinite loops are limited, but they do exist. The program below is definitely not useful, but does illistrate the idea of an infinite iteration:

1  class Prog36 {
2  
3    // A program to demonstrate infinite loops
4    public static void main(String[] args) {
5      int i = 1;
6  
7      for ( ; ; ) { // A 'forever' loop
8        System.out.println(i);
9        i = i * 2;
10     }
11   }
12 }
    

Just as any of the header sections of a for loop can be left empty, so can be body section. How is this useful? Surely a loop without a body is no good at all! Well, as we have already seen, it is possible to do quite a bit of work in the header of a for loop. If we revisit Prog35a you will notice that the only code in the loop body just prints out the current value of j. Since we only care about the final value of j we could move the call println outside the loop:

1  class Prog35c {
2
3    // A program to calculate the factorial of 11
4    public static void main(String[] args) {
5      int i, j, k;
6
7      for (i = 1, j = i, k = 11 ; i <= k; i = i + 1, j = j * i);
8      System.out.println(j);
9    }
10  }
    

Note the extra semicolon directly after the loop header. This is an empty statement, to let the compiler know that there is really nothing to do in the body of the loop. The call to println is not part of the loop.


Written by Scott Mitchell. Updated by Matthew Huntbach

These notes were produced as part of the course Introduction to Programming as it was given in the Department of Computer Science at Queen Mary, University of London during the academic years 1998-2001.

Last modified: 30 Sep 1999