Loops

Recall the three fundamental control constructs

Calling and returning from a method.

Conditional execution: either run some code or don’t based on some condition.

Looping: run some code repeatedly, while some condition holds.

Todays topic: Looping

while

The most primitive style of loop.

while (running) {
  doSomething();
}

Like an if the code inside the {}s only runs if the expression inside the ()s evaluates to true.

But it runs repeatedly until the condition is false.

Structure of a while

while (condition) {body}

The condition has to evaluate to a boolean.

The body can consist of any code.

Infinite loops

The body needs to change something so the condition will eventually become false or the loop will repeat infinitely.

Sometimes we want infinite loops

while (true) {
  String command = readCommand();
  execute(command);
}

Non-infinite while loops

Many while loops are written following this pattern:

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
}

for

Captures this common pattern.

The pattern

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
}

becomes

for (int i = 0; i < 10; i++) {
  System.out.println(i);
}

You will soon be able to write this loop header in your sleep.

If you start at 0 and loop while < n the loop runs n times.

Structure

for (initializer; condition; updater) {body}

Note the three clauses in the loop header are separated by semicolons.

Loops and return

public boolean hasX (String s) {
  for (int i = 0; i < s.length(); i++) {
    if (s.substring(i, i + 1).equals("X")) {
      return true;
    }
  }
  return false;
}

The return causes us to return immediately from the method.

The remaining iterations of the loop are abandoned.

Note the return false after the loop.

Choosing a loop

Use for when you know how many times the loop needs to run.

Use while when you don’t.

Snap! equivalents

(Roughly speaking)

while

for