For Loops

Another type of loop in Java is a for loop. This is usually used when you know how many times you want the loop to execute. It is often a simple counter-controlled loop to do the loop body a set number of times.

Three Parts of a For Loop

A for-loop combines all 3 parts of writing a loop in one line to initialize, test, and change the loop control variable. The 3 parts are separated by semicolons (;). Each of the three parts of a for loop declaration is optional (initialization, condition, and change), but the semicolons are not optional.

for (initialize; test condition; change) {
   loop body
}

The for-loop is almost a shortcut way to write a while loop with all three steps that you need in one line. One of the strange things about a for loop is that the code doesn’t actually execute where you see it in the declaration. The code in the initialization area is executed only one time before the loop begins, the test condition is checked each time through the loop and the loop continues as long as the condition is true, and the loop control variable change is done at the end of each execution of the body of the loop, just like a while loop. When the loop condition is false, execution will continue at the next statement after the body of the loop.

../_images/ForLoopFlow.png

Figure 2: Control flow in a for loop

You can compare a while loop to a for loop to understand that a for loop actually executes like a while loop does if you use the while loop to repeat the body of the loop a specific number of times.

../_images/compareForAndWhile.png

Figure 3: Showing how a for loop maps to a while loop

coding exercise Coding Exercise

The E01ForLoop program contains a for loop that counts from 1 to 5. Can you change it to count from 2 to 10?

The E02ForLoopFromWhile program contains a while loop that counts from 5 to 10. Run it and see what it does. Can you change it to a for-loop? Run your for-loop. Does it do the same thing?

Note

Two common patterns in for-loops are to count from 0 up to an number (using <) or count from 1 to the number including the number (using <=). Remember that if you start at 0 use <, and if you start at 1, use <=. The two loops below using these two patterns both run 10 times. The variable i (for index) is often used as a counter in for-loops.

// These loops both run 10 times
// If you start at 0, use <
for(int i = 0; i < 10; i++) {
   System.out.println(i);
}
// If you start at 1, use <=
for(int i = 1; i <= 10; i++) {
   System.out.println(i);
}

exercise Check your understanding

The following method has the correct code to print out all the even values from 0 to the value of 10, but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly. Even though Java doesn’t require indention it is a good habit to get into. You will be told if any of the blocks are in the wrong order or not indented correctly when you click the “Check Me” button.

Decrementing Loops

You can also count backwards in a loop starting from the last number and decrementing down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop. For example, “for (int i=5; i > 0; i–)`` counts from 5 down to 1.

coding exercise Coding Exercise

What do you think will happen when you run the E03SongTest program? How would it change if you changed line 11 to initialize i’s value to 3? Try using the debugger to trace through this code.

The program prints the words to a song. It initializes the value of the variable i equal to 5 and then checks if i is greater than 0. Since 5 is greater than 0, the body of the loop executes. Before the condition is checked again, i is decreased by 1. When the value in i is equal to 0 the loop stops executing.

Can you make the loop in E04ForLoopBackwards count by 2s backwards? It should print out 5 3 1? Remember to change all 3 parts of the for loop.

Summary

  • There are three parts in a for loop header: the initialization, the test condition (a Boolean expression), and an increment or decrement statement to change the loop control variable.

  • In a for loop, the initialization statement is only executed once before the evaluation of the test Boolean expression. The variable being initialized is referred to as a loop control variable.

  • In each iteration of a for loop, the increment or decrement statement is executed after the entire loop body is executed and before the Boolean expression is evaluated again.

  • A for loop can be rewritten into an equivalent while loop and vice versa.

You have attempted of activities on this page