While the while loop is all we need to be able to provide the repetition component required by any algorithm, itβs a little bit primitive. It has itβs uses but the real workhorse loop in Java is the for loop.
If you took AP CSP with a block programming language like Snap! you almost certainly used a for loop block like the one shown below. It is a bit more limited than a Java for loop but in simple cases, such as shown on the right below, they are essentially the same.
The purpose of a for loop is to provide a structure that gives us an easy way to put all three of those parts into the loop header instead of having to remember to initialize the loop variable before the loop and to remember to update the loop variable before the end of the body the way we have to do in a while loop.
So instead of a single boolean condition as we have in a while loop, the stuff in parentheses is a bit more complicated: three parts separated by semicolons (;).
Here is a control flow diagram for a for loop. If you compare this to the flow chart for of a while loop from in the previous section, youβll see that the main difference is that some parts that werenβt explicitly part of the while loop now get their own nodes in the chart.
The first item in the parentheses of the for loop header is, the initializer is a single statement that initializes the loop variable. Usually it also declares the variable, like int i = 0. As you can see from the flow chart, the initializer runs just once at the beginning of the loop.
After the initializer comes the condition, a boolean expression that acts just like the condition in a while loop; as long as it is true the loop body executes. When it is true the program proceeds to the body. When the condition is false we leave the loop and go to whatever comes after it in the program.
The final item in parentheses, the updater, is a statement that, as the flow chart shows, runs immediately after the body. Its job is to update the loop variable before control loops back to the condition.
Two of the most common ways to use a for loops is 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);
}
Subsection5.2.2Equivalence of for and while loops.
You may be thinking that there doesnβt seem to be anything you can do with a for loop that you canβt do with a while loop. And youβd be right. In fact it is completely straight forward to translate between the two.
For a very good walkthrough of how for and while loops are equivalent, watch the following video which compares a while loop and for loop line by line.
So why have both kinds of loops? And which should we use when? Since anything we can write with one, we can write with the other, it really comes down to convenience and expressing our intent.
The advantage of the for loop is that we can see at a glance, by looking at the loop header the overall structure of the loop: where the loop variable starts, what the loopβs condition is, and how the loop variable changes on each iteration of the loop. So when a loop is simple and fits into the pattern of a basic counting loop it makes sense to use a for loop. Itβs easy to read once you get used to it and itβs a signal that this is just a regular loop.
The while loop, on the other hand, is infinitely flexible. Itβs great, as we saw in the last chapter, for loops where we donβt know how many times the loop is going to execute until weβve run it. And in even more complex loops where maybe thereβs some complicated code to decide how to update the loop variable, or maybe when there are multiple loop variables, trying to fit all that into a for loop header is going to get to complicated. In that case a while loop is a better choice.
Here is 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?
This would be true if the for loop was missing the change part (int i = 3; i < 8; ) but it does increment i in the change part (int i = 3; i < 8; i++).
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.
You can also write forloops that count backwards starting at a big number and decrementing the loop variable until it is some small number, usually 0 or 1. If you want to change a forwards loop into a backwards loop that runs with the same values of the loop variable, just counting down instead of up, all three parts of the loop header must change. For example, the forwards loop on the left which starts at 1 and goes up to 5 has to change to the backwards loop on the right to count down from 5 down to 1.
What do you think will happen when you run the code below? How would it change if you changed the initializer to start iβs value at 3? Try the Code Lens button to visualize and trace through this code.
The program above prints the words to a song. It initializes the value of the variable i 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 of i is 0 it is no longer greater than 0 and the loop stops executing.
Complete the drawTriangle method to use a for loop to draw an equilateral triangle. How many times should the loop run? It ran 4 times for a square, so how many for a triangle? What angle should you use for the turns? One way to figure this out is to notice that to complete a shape, all the exterior angles should add up to 360 degrees. So, for a square 4x90 = 360. What angle times 3 will give you 360?
Complete the drawPentagon method to use a for loop to draw a pentagon (which has 5 sides and looks like a stop sign). What external angle should you use for the turns? Remember they have to add up to 360 degrees after 5 turns.
Complete the drawPolygon method to use a for loop to draw any polygong with n sides of length pixels given as arguments. Use n in your loop for the number of sides (or the number of iterations). Use pixels for the amount to move forward. Calculate the angle to turn by using a formula that uses n and 360, so that n turns add up to 360 degrees.
In the main method, call the drawPolygon method to draw a hexagon (6 sides). This method can draw a variety of shapes by just changing the value of the argument n. The power of abstraction! Try drawing other shapes with it. Note that if the turtle runs into walls, it stays there and will mess up the shape, so you may have to move the turtle or go forward smaller amounts.
Complete the methods below with for-loops to draw a square, triangle, pentagon, and then any polygon using a variable n that holds the number of sides. Add 1 more call to the method drawShapes in main. Note that the angles in the turns have to add up to 360.
(AP 2.8.A.1) A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization (of the loop control variable or counter), the Boolean expression (testing the loop variable), and the update (to change the loop variable).
(AP 2.8.A.2) In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable.
(AP 2.8.A.2) The for loop Boolean expression is evaluated immediately after the loop control variable is initialized and then followed by each execution of the increment (or update) statement until it is false.
(AP 2.8.A.2) In each iteration of the for loop, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
I. int sum = 0;
for (int count = 0; count <= 6; count++) {
count++;
if (count % 2 == 0) {
sum += count;
}
}
System.out.println(sum);
II. int sum = 0;
for (int i = 0; i <= 6; i += 2) {
sum += i;
}
System.out.println(sum);
III. int sum = 0;
for (int j = 7; j > 1; j--) {
if (j % 2 == 0) {
sum += j;
}
}
System.out.println(sum);