Radford University ITEC

ITEC120-ibarland (incl. office hrs)infolectureslabshws

loops, cont.

Things to think about, when writing loops

The purpose of a loop statement is to separate two different tasks: doing some task (once), and controlling the program to do the task over and over. Before writing a loop, think about what the particular task is, before you try to do it many times! Often, it is helpful to write this task as its own separate function, and just have your loop call that function.

Loop problems

We spend the week writing more functions involving loops. source code

loop syntaxes

Here is the syntax of various loop constructs, as applied to common situations:
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.

ITEC120-ibarland (incl. office hrs)infolectureslabshws


©2006, Ian Barland, Radford University
Last modified 2006.Nov.06 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme