Held Monday, September 13, 1999
Overview
Today, we'll continue our investigation of Java's control structures
by considering two control structures that permit you to do things
repeatedly: while loops and for loops.
After a short lecture/discussion, we'll spend most of today's class
on lab J5.
Notes
- Reminder: Mr. Stone will be visiting class this week as part of my
3rd-year review.
- Are there any final questions on
assignment 1?
- Wednesday's class will be mostly lecture/recitation. Please read
only the ``Exceptions'' section of
lab X3.
Contents
Handouts
Summary
- The need for repetition
- Two kinds: predetermined number and indeterminate
- Two looping structures
-
while loops (primarily indeterminate)
-
for loops (primarily predetermined)
- Lab: J5 (only J5.1 and J5.3)
- Due tomorrow: Assignment 1
- For Wednesday, read the section entitled ``Exceptions'' in
lab X3
- 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?
- 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 the first two.
- 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.
- 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.
- 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?
Tuesday, 10 August 1999
- Created as a blank outline.
Monday, 13 September 1999
- Added notes and overview.
- Incorporated
outline 7 of
CS152 99S.
- Reformatted that newly-incorporated text.
- Added example for
while loops.
- Added introduction to looping structures.
Back to Conditionals.
On to When Things Go Wrong.