Please enable JavaScript to use CodeHS

CodeHS Glossary


Fencepost Problem General

The fencepost problem is a problem when using a while loop where you forget one action at the beginning or the end. It comes from when you have a fence that is 4 feet long, and you want to make a post every foot along the fence. Even though the fence is 4 feet long, you actually need 5 posts, since there is one on each end and 3 in the middle. For a fence that is `N` feet long, you always need `N+1` posts. ---------- This happens when we write programs with a while loop. Let's say we have a program where there is a row of tennis balls, and Karel needs to pick all of them up. If we write while (frontIsClear()) { takeBall(); move(); } we actually don't take the last tennis ball at the end. This is a fencepost problem, since we have one more ball to take, but we have to cal `takeBall();` *after* the while loop ends like this: while (frontIsClear()) { takeBall(); move(); } takeBall(); // takes the last ball ---------- There are two ways to solve a fencepost problem. One is like we just did where we do one more action at the end. The other way is to flip the order of the commands inside the while loop and do the extra action at the beginning like this: takeBall(); // takes the ball in the first spot while (frontIsClear()) { move(); takeBall(); // we now move before taking a ball } Sometimes, it can be helpful for solving a problem to use method #1, but other times, using method #2 is a better way to solve something.