# Class 11: Lab: Loops

Back to Lab: Conditionals. On to When Things Go Wrong.

Held Wednesday, February 9, 2000

Overview

Today we continue to consider the control structures of Java by looking at two structures for repetition: while loops and for loops. Most of today's class will be devoted to lab.

Notes

• CS152 at a glance lists a homework as being due this Friday (or did until today). No homework will be due this Friday (or even next week).
• I should be distributing the first exam this Friday. It will be due the following Friday.
• In case I hadn't made it clear, I expect to post some of your work to the World Wide Web. If you have difficulties with this policy, please let me know as soon as possible.
• Read lab X3 for Friday.

Contents

Summary

• Project selection
• The need for repetition
• Primary looping control structures:
• `for` loops
• `while` loops
• Lab J5: Control Structures for Repetition
• Distributed:
• Java Plus Data Structures, Chapters 4, 5, 6, and 11
• Due:
• Preparatory reading of Lab J5

## Selecting Our Game

• You can vote for as many games as you like, but only once per game.
• Vivek will help me count.
• The games: = Bubble Bobble
• Calvinball (Is this just scorched earth?)
• Checkers
• Chess
• Civilization
• Einstein and the Squirrel
• Five in a row
• Othello
• PacMan
• Pollination
• Poobie the Penguin
• Scorched Earth (Vaccinate the Squirrel)
• Shoot the Dummies
• SimGrinnell
• Snowfighting
• Terrace
• Walking Through Fruit Trees
• Where in Grinnell is Carmen Sandiego?

## Control Structures for Repetition

• 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 the first two.

### While Loops

• 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();
while (!done) {
}
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.

### For loops

• 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.

#### Detour: Shorthand in Loops

• Most Java programmers increment their counter variables with the preincrement or postincrement operator, `var++`.
```    for (i = 1; i <= n; ++i)
```
• 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)
```

## Loop Lab

• Lab J5: Control Structures for Repetition
• Try to do experiment J5.1 during class. J5.1 covers `while` loops.
• Try to do J5.3 for Friday. J5.3 covers `for` loops.

### Reflect

• What does your `count` method look like?
• What is wrong with `readPass`. How did you fix that problem?

## History

Tuesday, 18 January 2000

• Created as a blank outline.

Wednesday, 9 February 2000

Back to Lab: Conditionals. On to When Things Go Wrong.

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.