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.


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.


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 i = 3?

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) Here are all the values of i (5, 4, 3, 2, 1) that allow the loop to run. When i is 0 the condition is false and execution continues after the body of the loop.

Check your understanding

Mixed up programs

Next Section - Nested For Loops