The for Loop
A
for loop puts the three parts of a counting loop in one header. This loop prints door labels for apartments 201 through 206 on one floor of a building.The header
for (int unit = 201; unit <= 206; unit++)
{
System.out.println("Apartment " + unit);
}
Semicolons split the parentheses into three parts. First,
int unit = 201 declares unit and starts it at 201; this part is the initialization. Next, unit <= 206 decides whether another pass happens; it's the Boolean expression. Last, unit++ adds 1 to unit after each pass, and it's called the update. The braces hold what repeats. The segment prints six lines, from Apartment 201 to Apartment 206.The order of events
For the apartment loop, the events run in this order.
unit = 201 initialization, once
unit <= 206 true body prints Apartment 201, then unit++
unit <= 206 true body prints Apartment 202, then unit++
...
unit <= 206 true body prints Apartment 206, then unit++
unit <= 206 false the loop ends (unit is 207)
Six passes mean six updates, and a seventh check of
unit <= 206 fails and ends the loop. With a step of 1 and <=, subtract the first value from the last and add 1: 206 minus 201, plus 1, gives 6. The extra 1 is there because both 201 and 206 are printed.Matching a header to a range
To fit a header to a range of values, put the first value in the first part, the step in the third, and the last value in the comparison. The even-numbered apartments, 202 through 206, need a first value of 202, a step of 2, and a last value of 206.
for (int unit = 202; unit <= 206; unit = unit + 2)
The expression
unit < 208 gives the same passes as unit <= 206 here, since unit is always even and never equals 207. When the operator changes, the number usually has to change with it, or the loop runs once more or once less.After the loop
A header variable like
unit is out of scope once the loop ends. To use its value afterward, declare it before the loop.int unit;
for (unit = 202; unit <= 206; unit = unit + 2)
{
System.out.println("Apartment " + unit);
}
System.out.println(unit);
The last line prints 208. The loop ended because 208 made
unit <= 206 false, and the variable still holds that value. No apartment on the floor is numbered 208.