Java Reference
In-Depth Information
Count the number of iterations to check that your for loop is correct.
Counting the number of iterations is a very useful device for better understanding a
loop. Counting is easier for loops with asymmetric bounds. The loop
for (i = a; i < b; i++) . . .
252
253
is executed b Ċ a times. For example, the loop traversing the characters in a
string,
for (i = 0; i < str.length(); i++) . . .
runs str.length() times. That makes perfect sense, because there are
str.length() characters in a string.
The loop with symmetric bounds,
for (i = a; i <= b; i++)
is executed b Ċ a + 1 times. That Ȓ + 1 ȓ is the source of many programming
errors. For example,
for (n = 0; n <= 10; n++)
runs 11 times. Maybe that is what you want; if not, start at 1 or use < 10 .
One way to visualize this Ȓ + 1 ȓ error is to think of the posts and sections of a
fence. Suppose the fence has ten sections ( = ). How many posts ( | ) does it have?
|=|=|=|=|=|=|=|=|=|=|
A fence with ten sections has eleven posts. Each section has one post to the left,
and there is one more post after the last section. Forgetting to count the last
iteration of a Ȓ <= ȓ loop is often called a Ȓfence post errorȓ.
If the increment is a value c other than 1, and c divides b Ċ a , then the counts are
(b - a) / c for the asymmetric loop
(b - a) / c + 1 for the symmetric loop
Search WWH ::




Custom Search