This book is now obsolete Please use CSAwesome instead.
7.3. For Loops¶
A for loop is usually used when you know how many times you want the loop to execute. A for loop has 3 parts: initialization, condition, and change. The 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 (initialization; condition; change)
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 condition is checked each time through the loop and the loop continues as long as the condition is true, at the end of each execution of the body of the loop the changes are done. When the loop condition is false execution will continue at the next statement after the body of the 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.
6-3-1: What do you think will happen when you run the code below? How would it change if you changed line 11 to <code>i = 3</code>?
The method printPopSong 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.
The number of times a loop executes can be calculated by (largestValue - smallestValue + 1). By the largest value I mean the largest value that allows the loop to execute and by the smallest value I mean the smallest value that allows the loop to execute. So in the code above the largest value is 5 and the smallest value that allows the loop to execute is 1 so this loop executes (5 - 1 + 1 = 5 times).
How many times does the code above print the lines to the song?
You can also calculate the number of times a loop executes as the value that ends the loop minus the starting value. In this case the loop ends when i is 3 so (3 - 0 = 3).
Check your understanding
Mixed up programs
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.