Java Reference
In-Depth Information
Figure 5.4
A flawed fence
Because you want posts on both the far left and the far right, you can't use the fol-
lowing simple loop (it doesn't plant the final post):
for (the length of the fence) {
plant a post.
attach some wire.
}
If you use the preceding loop, you'll get a fence that looks like Figure 5.4.
Switching the order of the two operations doesn't help, because then you miss the
first post. The problem with this loop is that it produces the same number of posts as
sections of wire, but we know we need an extra post. That's why this problem is also
sometimes referred to as the “loop and a half ” problem—we want to execute one half
of this loop (planting a post) one additional time.
One solution is to plant one of the posts either before or after the loop. The usual
solution is to do it before:
plant a post.
for (the length of the fence) {
attach some wire.
plant a post.
}
Notice that the order of the two operations in the body of the loop is now reversed
because the initial post is planted before the loop is entered.
As a simple example, consider the problem of writing out the integers between 1
and 10, separated by commas. In other words, we want to get the following output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
This task is a classic fencepost problem because we want to write out 10 numbers
but only 9 commas. In our fencepost terminology, writing a number is the “post” part
of the task and writing a comma is the “wire” part. So, implementing the pseudocode
we developed, we print the first number before the loop:
System.out.print(1);
for (int i = 2; i <= 10; i++) {
 
Search WWH ::




Custom Search