home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.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
-
loop-variable initialization
-
a loop-condition
-
an end-of-loop update to the loop-variable.
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.
|
-
Counting over [start,stop):
doing a task for
start,
start+1,
start+2,
…
stop-1.
As we've seen before, it's handy to use a half-open interval:
- The size of [a,b) is b-a (not b-a+1 or b-a-1 or anything).
In particular, [a,a) is the empty set
(there are no numbers which are ≥a (the left endpoint)
and are <a (the right endpoint).
- The interval [0,100) = [0,50) ∪ [50,75) ∪ [75,100);
we don't need to be constantly twiddling an endpoint by one to get our
intervals to align.
(You can also count down instead of up,
or step by a different amount than 1 each time.)
- iterators:
Iterators are anything with a boolean hasNext() method
and a next() method.
One example is java.util.Scanner
(which has the methods
int nextInt(),
double nextDouble,
and
String nextLine,
in addition to String next(),
as seen in the program for reading a web page).
The for-each loop applies to any Collection as well as any
Iterator, as we saw in the example programs
about File.listFiles().
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
-
loop-variable initialization
-
a loop-condition
-
an end-of-loop update to the loop-variable.
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,
-
for-each loops are preferred when you handle each element of
a collection the same, since they
keep loop-control logic in the background, letting a reader
concentrate on what the loop is doing.
- for loops are preferred over while loops, when convenient,
since they keep the loop-control logic all on one line.
- A while loop is preferred when a for-loop isn't convenient.
For example, while (scan.hasNext()) { process( scan.next() ); }
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.
↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs