1-8 The for Loop

Many algorithms require code to be repeated over and over again until some condition has been satisfied. Java supports three types of loops that all repeat code, however, they have some important structural differences that we will highlight as we go along.

Any loop structure requires 4 essential ingredients:

    1. control variable to keep track of and eventually stop the loop from iterating
    2. initial value for the control variable
    3. step expression to modify the control variable each time the loop iterates
    4. loop-continuation condition that determines if iteration should continue or not

The for loop is ideal for repeating a block of code a specific number of times. Here is a program that reads exactly 5 integers from the user and displays their sum:

Enter a series of 5 integers:
1
2
3
4
5
The sum of 5 integers entered is: 15

Programmers find the for loop easy to understand because all of the loop details are together at the top. The heart of the for loop is line 13; it contains all 4 loop ingredients.

1-8-forLoop

After the keyword for, and between parentheses ( .. ), are three expressions separated by semi-colons. The first expression declares the loop control variable and gives it an initial value. This expression only executes once when the loop starts. The second expression is the loop continuation condition. As long as this condition (counter < 5) is true, the loop body will iterate. After the loop body has been executed, the step expression (counter++) is run before the loop continuation condition is checked again. You can imagine the step expression happening as the last line in the body of the loop if this helps your understanding.  The cycle then repeats.

The for loop control variable often keeps track of the number of iterations of the loop body. For this reason, the for loop is referred to as a counter-controlled loop. Also, because the loop continuation condition is checked before the body of the loop iterates (even the first time) it is a pre-test loop.

You’ll notice that the counter variable is declared in the first expression of the for loop header, it is not declared as you might expect at the top of the main() method like input and sum. The impact of this is that you can only refer to the counter variable inside the loop body code, not outside.

Finally, like an if statement, if the body of a for loop only contains 1 statement, the curly braces { .. } are optional but highly recommended to avoid logic errors.

Nested Control Structures

On their own, the selection and iteration structures we have covered so far are already pretty useful, but they become even more powerful when nested. Nesting means putting one control structure inside another.

Here’s an example that analyses exam results to determine whether a school should raise tuition or not. Here we’re nesting an if..else statement within a for loop.

Test this code yourself to see how it works.

Notice in the final output statement I’ve used the format specifier %5.1f to display the pass percentage as 5 digits, including the decimal point and one digit after the decimal point (rounded). To display a single % sign in the output I’ve also used the %% format specifier. Lastly, to ensure that the result of the calculation is a floating-point value rather than an integer, I’ve divided passes by the double value 9.0.

The continue Statement

Sometimes it can be handy to be able to skip any remaining code in the current iteration of a loop body and immediately start the next iteration. To do this in Java we use the continue statement. Here’s a program that counts backwards from 5, but when countDown equals 3 the rest of the code in the for loop body is skipped, and the next iteration starts; meaning that the step expression is executed and then the loop continuation condition is checked. As long as the loop continuation condition is still true the body is then executed again.

5 4 (skipping 3) 2 1 … Blast-off!

You Try!

    1. Analyse the following nested for loop to determine the output. Then, try it in Dr Java to see if you are right.