RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect13a
for loops

for loops

In addition to for-each loops and while-loops, java also has for-loop (sometimes called an “old-school for loop”, since it actually predated the for-each loop).

an example

As we saw last time, a while-loop can do everything a for-each loop can do. Here's a for-each loop which sums the ages of Dogs in a list:

// A loop to add all the ages of every Dog in doggies.
int agesSoFar = 0;
for ( Dog d : doggies ) {
  agesSoFar = agesSoFar + d.getAge();
  }
Here's the same thing, but using a while loop:
int agesSoFar = 0;
int index = 0;
Dog d;
while ( index < doggies.size() ) {
  d = doggies.get( index );
  agesSoFar = agesSoFar + d.getAge();
  index = index +1;
  }
Note that it's not strictly necessary to have a local variable d. Practice: re-write this code without using d. Here's the exact same task, written using this new “for” loop:
int totalAgeSoFar = 0;
Dog d;
for ( int index = 0;  index < doggies.size();  index=index+1 ) {
  d = doggies.get(index);
  totalAgeSoFar = totalAgeSoFar + d.getAge();
  }
      
Note that both loops have These three parts are all dealing with the loop's control-logic. In the for loop, all three occur together on the same line. Notice that they are separated by semicolons (“;”).

optional shorthand:

Note that for loops are one place where “++index” is used instead of “index = index+1”, or even “index += 1”. Still, when using the

Remember: When using the ++ operator, use it as a statement by itself -- not combined with the assignment statement “=” or any other statement.
(The combination may be legal java syntax, yet is almost certainly not what you want.)

practice (lab): write a static method countVowels(String): First using while, and then using for

Syntax

Typically, for loops are used for counting from start to stop:

for (int index = start; index < stop; ++index ) {
  statements...
  }
The above example uses 0 for start, and doggies.size() for stop.

But for loops are actually as general as while loops. The general syntax of the for loop is:

for (statementinit; condition; end-of-loop-update) {
  statements...
  }
Note that where the for-each loop used a colon (“:”) to separate the variable-declaration and the list-to-iterate-over, the for loop uses two semicolons to separate the statementinit, the condition, and the end-of-loop-update.

loop syntaxes

Here is a summary of various loop constructs, as applied to common situations. Note that the table includes iterators (which includes Scanners), even though we won't talked about iterators in this course (beyond the one example of a Scanner… and Random).
while loops for for-each
counting over [start, stop)
int index = start;
while (index < stop) {
  statements...
  index = index + 1;
  }
This is a bit more awkward than the corresponding for-loop.
for (int index = start; index < stop; ++index ) {
  statements...
  }
[not applicable]
iterators
Iterator it = expressioniterator;
while (it.hasNext()) { 
  variable = it.next();
  statements...involving variable
  }
for (Iterator it = expressioniterator; it.hasNext(); /* no update */ ) {
  variable = it.next();
  statements...involving variable
  }
This is a bit more awkward than the corresponding while-loop.
for ( variable : expressioniterator ) {
  statements...involving variable
  } 
general syntax
statementinit;
while (condition) {
  statements...
  }
for (statementinit; condition; end-of-loop-update) {
  statements...
  }
for ( variable : expressioniterator-or-collection) {
  statements...involving variable
  }
This is very natural when you have a iterator or a collection and you want to process each item, but you don't care about which order the items are processed in. This is the one loop where break can be necessary.

There is also the do-while loop, as in the book. Each of these admit the break statement, which is handiest when searching using a for-each: that is, as soon as you find a matching item you want to break out of the loop.

Pragmatics of while vs. for

The two loops are equivalent -- anything you can write using a while-loop, you can write using a for-loop (and &vv;). (This is in contrast to for-each loops, which are strictly more limited.) In fact, there's a mechanical translation between while and for: just identifying the

and arranging them appropriately.1

Q: When is for more apropriate?
A: When counting, or when you can tell in advance exactly how many times you'll go through the loop, or when there is exactly one loop variable, which is always updated in the same way.

Q: When is while more apropriate?
A: Whenever a for-loop isn't :-) That is, when there is no clear loop variable, or the end-of-loop update is more than a few words (or it's absent entirely).

In general,

1Conceivably, the end-of-loop update could be do-nothing-at-all, in which case there is nothing between the second semicolon and the closing parenthesis of the for-loop.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Jan.24 (Thu)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme