next up previous contents
Next: While loops Up: 3 Iteration Previous: 3 Iteration   Contents

For loops

Here is an example of a for loop:

for (int i=0; i<10; i++)
{
    System.out.println(i);
}

The first line, starting with the for statement, defines the loop. The code to be executed inside the loop is contained within the curly brackets, {}. Code within these brackets is indented to make it easier to see that it is inside the loop.

There are three expressions within the round brackets after the for statement. The first (int i=0) is known as the initial expression. It is used to do things like declare and initialise variables before the loop starts. It is evaluated only once. The second expression within the round brackets (i<10) is the test expression. This is evaluated at the beginning of each iteration. It must be a logical expression, as described in the previous section on if statements. If it is found to be true, the iteration continues and the code within the loop is executed. If false, the loop ends. The final expression within the round brackets (i++) is the update expression. This is evaluated at the end of each iteration, after the code within the loop has been executed.

In the example, i is declared as an int and initialised to 0. Then the test i<10 is evaluated. This is clearly true since i is 0. So the line of code inside the loop is executed with the result that the value of i, 0, is printed to the screen. The update expression i++ is short-hand for i = i + 1, i.e. the value of i is increased by one. This is repeated until it is no longer true that i is less than 10. At this point, the test fails and the loop ends.

Exercise 3.1


(4 marks)



First, predict exactly what numbers the above code would print out. What are the first and last numbers that will be printed? Explain your reasoning. Then, write a program containing the above code, run it and compare the results with your prediction. If you got it wrong, explain what actually happened and why.



Note: the + + operator is very useful in loops. There is also a - - operator, which does the opposite, i.e. subtracts 1 from the variable.

You can put any valid Java code inside the for loop. For example, variable declarations, if statements, calculations, mathematical functions, and even another loops.


next up previous contents
Next: While loops Up: 3 Iteration Previous: 3 Iteration   Contents
RHUL Dept. of Physics