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 is optional, but the semicolons are not optional.

for (initialization; condition; change)

The code in the initialization area is executed before the first execution of the loop, 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.



        

( lcfc1 )

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 times a loop executes can be calculated by (largestValue - smallestValue + 1). So in this case the smallest value is 1 and the largest is 5 so this loop executes (5 - 1 + 1) 5 times.

Check your understanding

6-2-1: What does the following code print?

for (int i = 3; i < 8; i++)
{
   System.out.print(i + " ");
}





6-2-2: What does the following code print?

for (int i = 1; i <= 10; i++)
{
   System.out.print(i + " ");
}





6-2-3: How many times does the following method print a *?

for (int i = 3; i <= 9; i++)
{
   System.out.print("*");
}





Mixed up programs

6-2-4: 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. You will be told if any of the blocks are in the wrong order or not indented correctly.