ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Loop the Loop
Subject:   observations, suggestions, and a bug
Date:   2003-10-11 09:41:37
From:   anonymous2
Even given that ten different programmers would write a given program in ten different ways, I'd like to offer a few thoughts on the provided code samples.


The relevant portions of the first example are:

int loopsPerformed = 1;
while( loopsPerformed <= loopsToPerform ) {
//do stuff
loopsPerformed++;
}
</code>
Two observations here: loopsPerformed is always too large at the beginning of the loop (it begins at 1, before the loop body is ever entered), and incrementing a counter at the end of a loop can be easy to forget.


I believe it is more clear to write this as:

int loopsPerformed = 0;
while( loopsPerformed < loopsToPerform ) {
++loopsPerformed;
//do stuff
}


This idea of keeping the loopsPerformed accurate in the condition clause carries over to the 'for' loop at the end of the article. Instead of

for( loopsPerformed = 1; loopsPerformed <= loopsToPerform; loopsPerformed++ )
</code>
consider

for( loopsPerformed = 0; loopsPerformed < loopsToPerform; loopsPerformed++ )


...which leads us to the bug. The first 'do' loop example contains:

int loopsPerformed = 0;
do {
loopsPerformed++;
} while ( loopsToPerform >= loopsPerformed );

If loopsToPerform == 1, then we go through the loop TWICE, and print 2 as the favorite. Similarly, if loopsToPerform == 2, then we go through the loop THRICE, and print 3 as the favourite.


Since loopsPerformed is accurate in this example (it's zero before the loop body is ever executed, and at the condition it accurately reflects the number of times the loop has been executed), the condition needs to be written to reflect this:

int loopsPerformed = 0;
do {
loopsPerformed++;
} while ( loopsToPerform > loopsPerformed );

Submitted with only good intent,


--Glenn