Held Tuesday, September 12, 2000
Summary
Today we continue to consider the control structures of Java by looking at
two structures for repetition: while
loops, do
loops, and for
loops. Most of today's class will be devoted
to lab.
Notes
- Are there questions on
- For tomorrow:
- As I look at what I have to get done this week, I'm now shooting
for Friday for grading the first homework.
- As some of you have noted, our textbook uses some stuff that we haven't
covered yet. It also has a different I/O model than we use. (Java's
built-in I/O model is nice, but not necessarily for beginners.)
- The
for
loops we'll cover today.
- The
skipWhite
is a different I/O thingy.
- Let me know if you have other questions.
- I'll be handing out the first exam on Friday.
Overview
- The problem of repetition
- Repetition in Scheme
- Java's three looping constructs:
while
, do
,
and for
.
- In many algorithms, we want to be able to do the same thing repeatedly.
- Apply a function to each element of a list.
- Process information until there is no more information left to
process.
- Beat the mixture 40 times (recipe).
- Rather than repeating the code again and again, we look toward control
structures that let us express the repetition concisely and clearly.
- These are often called loops.
- What techniques did you use for repeating actions in Scheme?
- I would assume that recursion was your primary technique.
- Most imperative languages provide three kinds of control structures:
- One looping control structure supports a fixed number of repetitions
(beat the mixture 40 times; for each element of this list, do ...).
Often, this control structure gives you an associated counter
variable.
- A second looping control structure allows you to repeat an action
for as long as a condition holds (as long as there is work left to do
...).
- A third looping control structure allows you to repeat an action until
a condition holds (keep doing work until you've finished the project).
Obviously, this can be simulated by the prior structure.
- We'll look at how Java supports all three.
- To help you think about this stuff, we'll look at repetition in Scheme.
Consider the problem ``Given a list of numbers, create a new list that
contains the squares of the numbers in the first list.''
- How many ways do you know to solve this?
- Which are the most elegant?
- We'll begin with the second kind of looping structure, because it is
the most general.
- You will use this structure execute a series of statements as long as
a condition holds.
- For this case, Java provides
while
loops, which have the form
while (test) {
statements;
} // while
next-statement;
- In executing this loop, Java evaluates the test. If
the test fails, the loop terminates and Java moves on to the next
statement. Otherwise, Java executes the
statements in the body of the loop and then goes back and tries the
test again.
- For example, here's some simple code to read a series of grades and
stop when the user enters 0.
boolean done = false;
SimpleOutput pen = new SimpleOutput();
SimpleInput eyes = new SimpleInput();
int nextGrade = 0;
int numGrades = 0;
int sumGrades = 0;
while (!done) {
pen.print("Enter the next grade: ");
nextGrade = eyes.readInt();
if (nextGrade != 0) {
sumGrades = sumGrades + nextGrade;
numGrades = numGrades + 1;
}
else {
done = true;
}
} // while (!done)
- Note that the testing is only done when the body finishes. If the
body makes the test temporarily false and then true again, the loop
still continues.
- At times, you will want to have a loop in which the body is executed
once before the test. While it is possible to do this by repeating
code, it is easier to use a variant of the while loop
called the ``do loop''. This variant has the form
do {
statements
} while (test);
next-statement;
- This is the only time you won't need to comment your ending brace.
- If you only want to execute one (or zero) statements, you don't need
the braces. However, I consider it good programming practice to
include them.
- It doesn't change the execution speed of your program.
- It makes it much easier to extend your program.
- It does, however, increase the physical length of the code for
your program.
- Sometimes you want to execute the body of the loop once before
testing the condition.
- You can always copy the body of the loop, but that's dangerous
- It's hard to maintain duplicated code
-
do
loops turn while
loops around
- Here's the form
do {
body
} while (condition)
- At times, you want to execute a statement (or block of statements)
a fixed number of times.
- For example, to calculate the factorial of N, we might
multiply 1 by the numbers from one to N.
- Yes, this is a prototypical example.
- We might express this in psueodcode as
result = 1
for each value, v, between 1 and N
multiply result by v, updating result
return the final result
- Many programming languages provide a structure known as the
for loop for situations like this.
- Java provides a more general form of the for loop. It has the form
for (initialization; test; increment) {
statements;
} // for
- In effect, this is equivalent to
initialization;
while (test) {
statements;
increment;
} // while (test)
- Any of the four parts of a for loop can be omitted
(in which case it is ignored).
- We can then solve our initial factorial problem as follows
/**
* Compute n!.
*/
public int factorial(int n) {
int i; // A counter variable
int factorial; // The factorial of n
factorial = 1;
for (i = 1; i <= n; i = i+1) {
factorial = factorial * i;
} // for
return factorial;
} // factorial(int)
- We could also use while loops or recursive procedure calls.
- Most Java programmers increment their counter variables with
the preincrement or postincrement operator,
var++
.
- It is also possible (and even encouraged) to declare the counter
variable within the for loop, as in
for (int i = 1; i <= n; ++i)
- What does your
count
method look like?
- What is wrong with
readPass
. How did you fix that
problem?