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 (;).

Note

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.

../_images/ForLoopFlow.png

Figure 1: 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 1: Showing how a for loop maps to a while loop

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.

Note

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?

Note

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

You have attempted of activities on this page