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:
-
- control variable to keep track of and eventually stop the loop from iterating
- initial value for the control variable
- step expression to modify the control variable each time the loop iterates
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Scanner; public class ForLoop { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); int sum = 0; // Prompt the user to enter exactly 5 integers System.out.println( "Enter a series of 5 integers:" ); // for statement header includes control variable // initialization, continuation condition, and step expression for ( int counter = 0; counter < 5; counter++ ) { sum += input.nextInt(); } System.out.println( "The sum of 5 integers entered is: " + 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Scanner; public class NestedControl { public static void main( String[] args ) { // create Scanner to obtain input from keyboard Scanner input = new Scanner( System.in ); int passes = 0; int failures = 0; int studentCounter = 1; int result; // Process exactly 9 students using for loop for (int studentCount = 1; studentCount <= 9; studentCount++) { // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextInt(); // if...else nested inside for loop if ( result == 1 ) { passes = passes + 1; } else { failures = failures + 1; } } // Display analysis of results System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures ); System.out.printf( "%5.1f%% of students have passed.\n", ( passes / 9.0 * 100 ) ); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class ContinueLoop { public static void main( String[] args ) { for ( int countDown = 5; countDown > 0; countDown-- ) { if ( countDown == 3) { System.out.print( "(skipping 3) " ); continue; } System.out.print( countDown + " " ); } System.out.println( "... Blast-off!" ); } } |
5 4 (skipping 3) 2 1 … Blast-off!
You Try!
-
- Analyse the following nested for loop to determine the output. Then, try it in Dr Java to see if you are right.
123456789101112131415int counter1 = 0;int counter2 = 0;int counter3 = 0;int counter4 = 0;for ( int i = 0; i <= 4; ++i ) {counter1++;for ( int j = 0; j < 5; j++ ) {counter2 += counter1;if (i == j)counter3--;elsecounter4++;}}System.out.println( counter1 + " " + counter2 + " " + counter3 + " " + counter4 );
- Analyse the following nested for loop to determine the output. Then, try it in Dr Java to see if you are right.