Lecture 11 (Tychonievich) - Loops

Lecture Date: Friday 6 February

while (X) { Y; } means if (X) { Y; if (X) { Y; if (X) { Y; if (X) { ...: it repeats action Y as long as X is true.

for(X; Y; Z) { W; } is shorthand for { X; while (Y) { W; Z; } }. The first part sets up the loop; the second part is the guard or condition under which we repeat; the third is an update that happens at the end of each repetition: for(setup; guard; update) { action; }.

The most common use of a for loop is to repeat something a known number of times, almost always written as for (int i = 0; i < n; i += 1) { ... } where n is the number of times to repeat the action and i is the index or counter variable. It is in your interest to be able to write that for-loop automatically; I suggest writing it out by hand on paper a dozen times to help train your mind to produce it easily.

An aside: the following all increase x by one:

  • x = x + 1
  • x += 1
  • ++x
  • x++

We usually use while loops when we cannot predict how many times we’ll need to repeat something. Two common examples:

Reading all input
1
2
3
4
5
while (keyboard.hasNextInt()) { //              the hasNext____()
    int x = keyboard.nextInt(); // should match the    next____()
    // do something with x here
}
// when we get to this line, all ints have been read
Validating input
1
2
3
4
5
6
7
System.out.print("Type either y or n: ");
String typed = keyboard.next();
while (!typed.equals("y") && !typed.equals("n")) {
    System.out.print("I asked for either y or n, not \""+typed+"\"; try again: ");
    typed = keyboard.next();
}
// when we get to this line, typed is either "y" or "n"

You might also find a loop visualizer that I started writing few years ago helpful.

From lecture:

Code:

Audio: