Part 1 · The core language

4Loops

A program that can only run each statement once is not much use. This lesson teaches the three loops Java offers for repeating statements, and the one skill that makes loops understandable: tracing a loop by hand, one pass at a time, until you can say what it will do before the computer does it.

By the end you will be able to

  • write while, for and do-while loops, and say which of them fits a given job
  • trace a loop on paper with a table that shows every variable and the condition on every pass
  • write the standard loop patterns: counting, adding up, counting matches, and tracking the largest or smallest value
  • find and prevent off-by-one errors and infinite loops
  • use break and continue, and know when to avoid them
  • nest one loop inside another to print rows and columns

Why programs repeat

Adding up the numbers from 1 to 5 takes five statements. Adding up the numbers from 1 to 1,000 should not take a thousand. Worse, the amount of repetition is often not known when you write the program: how many digits does a number have, how many steps until a calculation settles, how many items are left to process? You need a way to say keep doing this for as long as it makes sense.

A loop is a statement that carries out a block of statements again and again. Each run through the block is called a pass (many books say iteration; it means the same). Java has three kinds of loop: while, for and do-while. They differ in how they are written and in when they decide to stop, but they all work the same way underneath, so we start with the simplest and build up.

The while loop

while (condition) {
    body
}

The condition is a boolean expression, exactly like the ones you wrote inside if in lesson 3. The body is the block of statements between the braces. The rules are short:

  1. Evaluate the condition.
  2. If it is true, run the whole body once, then go back to step 1.
  3. If it is false, skip the body and carry on with the first statement after the closing brace.

The condition is checked before each pass, including the first. The picture below shows the same rules as a flow.

before the loop set up the variables condition true or false? true the body runs once: one pass back to the test false after the loop the program goes on

Here is the smallest useful example. It counts down from 3.

code/m04-loops/Countdown.java
// Counts down from 3, then prints a closing message.
public class Countdown {
    public static void main(String[] args) {
        int n = 3;
        while (n > 0) {
            System.out.println("n is " + n);
            n = n - 1;
        }
        System.out.println("Beep!");
    }
}
Terminal, in code/m04-loops
> javac Countdown.java
> java Countdown
n is 3
n is 2
n is 1
Beep!

The output is easy to predict here, but the habit you are about to learn is for the cases where it is not.

Tracing

To trace a program is to play the part of the computer on paper: carry out the statements one at a time and write down what every variable holds after each step. For a loop, the tool is a trace table with one row per pass. It has a column for each variable that changes, and a column for the condition. Here is the table for Countdown:

passn at startn > 0printsn after the body
13truen is 32
22truen is 21
31truen is 10
check0false

Four rules make a trace reliable.

The table tells you three things at a glance. The body ran 3 times. The condition was evaluated 4 times: once per pass, plus the final check that stopped the loop. And after the loop, n is 0, not 1, because the update that made the condition false had already happened. A while loop that ends because its condition became false, after n passes, has checked the condition n + 1 times.

Nothing in the rules says the body must run at all. If the condition is false the first time it is checked, the loop does nothing and the program moves on. A while loop can run zero times.

Predict

Before reading on, draw a trace table for this program on paper, with columns for n at the start of the pass, the condition n > 1, n after the body, and steps after the body. Then write down the two lines it prints.

code/m04-loops/predict/Halve.java
public class Halve {
    public static void main(String[] args) {
        int n = 10;
        int steps = 0;
        while (n > 1) {
            n = n / 2;
            steps++;
        }
        System.out.println("n = " + n);
        System.out.println("steps = " + steps);
    }
}
Reveal the answer
passn at startn > 1n aftersteps after
110true51
25true22
32true13
check1false
Terminal, in code/m04-loops/predict
> javac Halve.java
> java Halve
n = 1
steps = 3

Whole-number division throws the fraction away (lesson 2), so 5 / 2 is 2, and the third pass turns 2 into 1. The loop stops when n reaches 1, so the program prints n = 1 and steps = 3. If your table gave something different, find the first row where it disagrees with this one. That row is where your picture of the program went wrong, which is exactly what tracing is for.

The loop variable and its update

Every counting loop needs three things, and it is worth naming them, because forgetting one is a common loop mistake.

JobWhere it isIn Countdown
Start: give the loop variable its first valuebefore the loopint n = 3;
Test: decide whether to run another passthe conditionn > 0
Update: change something the test looks atinside the bodyn = n - 1;

The loop variable is the variable that the condition examines and the body changes. The key requirement is that the update moves it towards the point where the condition becomes false. A loop with no working update repeats the same pass forever, because nothing ever changes the answer to the test. That is an infinite loop.

Here is Countdown with the update deleted. To make it safe to run, there is a second variable, safety, that counts the passes and stops the loop after five of them.

code/m04-loops/Stuck.java
// A loop whose update is missing. The safety counter is the only reason it stops.
public class Stuck {
    public static void main(String[] args) {
        int n = 3;
        int safety = 0;
        while (n > 0 && safety < 5) {
            System.out.println("n is " + n);
            safety++;
            // Forgotten: n = n - 1;
        }
        System.out.println("Stopped by the safety counter. n is still " + n);
    }
}
Terminal, in code/m04-loops
> javac Stuck.java
> java Stuck
n is 3
n is 3
n is 3
n is 3
n is 3
Stopped by the safety counter. n is still 3

Five identical lines. Trace it and you see why: n is 3 at the start of every pass, 3 > 0 is true every time, and the only variable that changes is safety. Without the safety counter in the condition (line 6), the program would print n is 3 for as long as you let it run.

If you ever run a program that does not stop, or that scrolls output endlessly, press Ctrl+C in the terminal. It ends the program that is running and returns you to the prompt. Click in the terminal first so that it has the keyboard focus, and make sure no text in it is selected, because with a selection Ctrl+C may copy instead of stopping the program. Then look for the loop whose test can never become false.

Forgetting the update is not the only cause. The update can also be there and still never produce the exact value the test is waiting for:

code/m04-loops/StepsOver.java
// A condition with != that the counter steps over. The safety counter ends the run.
public class StepsOver {
    public static void main(String[] args) {
        int n = 7;
        int safety = 0;
        while (n != 0 && safety < 6) {
            System.out.println("n is " + n);
            n -= 2;
            safety++;
        }
        System.out.println("Stopped by the safety counter. n is " + n);
    }
}
Terminal, in code/m04-loops
> javac StepsOver.java
> java StepsOver
n is 7
n is 5
n is 3
n is 1
n is -1
n is -3
Stopped by the safety counter. n is -5

The loop variable goes 7, 5, 3, 1, and then jumps over 0 to -1. The test n != 0 asks is it exactly 0?, and it never is. Writing n > 0 instead says is it still above 0?, which stays correct however the steps fall. When a loop counts towards a limit, prefer a test that uses <, <=, > or >= over !=.

Four patterns you will use constantly

Many loops you write in this course are one of four shapes, and recognising the shape tells you what the variables must look like before the loop starts. Each example below uses while, with its trace.

Counting

The simplest use of a loop is to run something a set number of times, using the loop variable itself as the thing being counted.

code/m04-loops/Squares.java
// Pattern: counting. The loop variable k is the thing being counted.
public class Squares {
    public static void main(String[] args) {
        int k = 1;
        while (k <= 5) {
            System.out.println(k + " squared is " + (k * k));
            k++;
        }
    }
}
Terminal, in code/m04-loops
> javac Squares.java
> java Squares
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
passk at startk <= 5printsk after
11true1 squared is 12
22true2 squared is 43
33true3 squared is 94
44true4 squared is 165
55true5 squared is 256
check6false

Accumulating a sum or a product

An accumulator is a variable that collects a result across passes. It is set to a starting value before the loop and updated from its own old value on every pass. For a sum, each pass adds something:

code/m04-loops/Sum.java
// Pattern: accumulating a sum. total starts at 0 and grows by i on every pass.
public class Sum {
    public static void main(String[] args) {
        int i = 1;
        int total = 0;
        while (i <= 5) {
            total = total + i;
            System.out.println("i = " + i + ", total = " + total);
            i++;
        }
        System.out.println("Sum of 1 to 5: " + total);
    }
}
Terminal, in code/m04-loops
> javac Sum.java
> java Sum
i = 1, total = 1
i = 2, total = 3
i = 3, total = 6
i = 4, total = 10
i = 5, total = 15
Sum of 1 to 5: 15

The program prints its own trace, so the output is the table: total after each pass is 1, 3, 6, 10, 15. The program prints total after it has been updated and i before i++ runs, so each printed i is the value from the at start column. The full table, with the i++ included:

passi at starti <= 5total beforetotal afteri after
11true012
22true133
33true364
44true6105
55true10156
check6false

A product works the same way with *, but the starting value matters. Adding 0 changes nothing, so a sum starts at 0. Multiplying by 1 changes nothing, so a product starts at 1. A product that starts at 0 stays 0 whatever you multiply it by.

code/m04-loops/Product.java
// Pattern: accumulating a product. product must start at 1, not 0.
public class Product {
    public static void main(String[] args) {
        int i = 1;
        int product = 1;
        while (i <= 5) {
            product = product * i;
            System.out.println("i = " + i + ", product = " + product);
            i++;
        }
        System.out.println("Product of 1 to 5: " + product);
    }
}
Terminal, in code/m04-loops
> javac Product.java
> java Product
i = 1, product = 1
i = 2, product = 2
i = 3, product = 6
i = 4, product = 24
i = 5, product = 120
Product of 1 to 5: 120

Again the printed lines are the trace: product after each pass is 1, 2, 6, 24 and 120.

Counting how many satisfy a condition

Here the loop looks at many values, and an if inside the body decides which of them count. The counter goes up only on the passes where the test is true.

code/m04-loops/CountMultiples.java
// Pattern: counting how many values satisfy a condition.
public class CountMultiples {
    public static void main(String[] args) {
        int n = 1;
        int count = 0;
        while (n <= 10) {
            if (n % 3 == 0) {
                count++;
            }
            n++;
        }
        System.out.println("Multiples of 3 from 1 to 10: " + count);
    }
}
Terminal, in code/m04-loops
> javac CountMultiples.java
> java CountMultiples
Multiples of 3 from 1 to 10: 3
n at startn <= 10n % 3 == 0count after
1truefalse0
2truefalse0
3truetrue1
4truefalse1
5truefalse1
6truetrue2
7truefalse2
8truefalse2
9truetrue3
10truefalse3
11 (check)false

Notice where n++ sits: outside the if, at the end of the body, so it runs on every pass. If you put it inside the if, n would stop moving at the first value that failed the test, and the loop would never end. Trace it if you doubt that.

Tracking the largest or smallest so far

To find the biggest value in a collection of values you keep one variable, the best so far, and compare each new value against it. You have no way yet to store a collection of values (that is lesson 7), so this program makes its values with a formula: (i * 37) % 11 gives a jumble of numbers between 0 and 10 that stands in for real data.

code/m04-loops/Extremes.java
// Pattern: tracking the largest and smallest value seen so far.
// The formula (i * 37) % 11 stands in for data. Its results are always 0 to 10.
public class Extremes {
    public static void main(String[] args) {
        int i = 1;
        int largest = 0;     // any value will be at least this big
        int smallest = 10;   // any value will be at most this big
        while (i <= 6) {
            int value = (i * 37) % 11;
            if (value > largest) {
                largest = value;
            }
            if (value < smallest) {
                smallest = value;
            }
            System.out.println("i = " + i + ", value = " + value
                    + ", largest = " + largest + ", smallest = " + smallest);
            i++;
        }
    }
}
Terminal, in code/m04-loops
> javac Extremes.java
> java Extremes
i = 1, value = 4, largest = 4, smallest = 4
i = 2, value = 8, largest = 8, smallest = 4
i = 3, value = 1, largest = 8, smallest = 1
i = 4, value = 5, largest = 8, smallest = 1
i = 5, value = 9, largest = 9, smallest = 1
i = 6, value = 2, largest = 9, smallest = 1
ivaluevalue > largestvalue < smallestlargest aftersmallest after
start010
14truetrue44
28truefalse84
31falsetrue81
45falsefalse81
59truefalse91
62falsefalse91

The starting values need thought. largest must start at something that any real value will beat, and smallest at something that any real value will undercut. Here the values are known to lie between 0 and 10, so 0 and 10 are safe. If you did not know the range, there are two safe choices. One is to start both variables with the first value itself and compare from the second onwards. The other uses the limits from lesson 2: start smallest at Integer.MAX_VALUE and largest at Integer.MIN_VALUE, because every int is at most the first and at least the second. Starting largest at 0 when the data can be negative is a classic bug: if every value is negative, the program reports 0, a number that was never in the data.

Here are the four patterns side by side. A sum and a product are one pattern with different starting values, so they get a row each.

PatternBefore the loopIn the body
Countingthe starting valueuse the loop variable; update it
Sumtotal = 0total = total + item
Productproduct = 1product = product * item
How many matchcount = 0if (test) { count++; }
Largest / smallesta value any item will beatif (item > largest) { largest = item; }

Off-by-one errors

An off-by-one error is a loop that runs one pass too many or one too few. It is one of the most common loop bugs, and it usually comes from choosing the wrong comparison (< instead of <=) or the wrong starting value (0 instead of 1). The program compiles, runs and gives an answer that is just slightly wrong. Both of the loops below are meant to add 1 + 2 + … + 10:

code/m04-loops/OffByOne.java
// Meant to add 1 + 2 + ... + 10. The first loop is off by one.
public class OffByOne {
    public static void main(String[] args) {
        int total = 0;
        int i = 1;
        while (i < 10) {
            total = total + i;
            i++;
        }
        System.out.println("With < 10:  " + total);

        total = 0;
        i = 1;
        while (i <= 10) {
            total = total + i;
            i++;
        }
        System.out.println("With <= 10: " + total);
    }
}
Terminal, in code/m04-loops
> javac OffByOne.java
> java OffByOne
With < 10:  45
With <= 10: 55

The first loop is wrong, and a trace shows why. Its rows look like the rows of any sum, and what matters is the end:

passi at starti < 10total after
11true1
22true3
33true6
…
88true36
99true45
check10false

When i reaches 10, the test 10 < 10 is false, so 10 is never added. The loop stopped one value early, and the trace shows it on the last two rows. The habit that catches this: when you trace a loop, always write out the first pass, the last pass and the final check. Off-by-one errors hide at those three places.

When the loop variable goes up by 1 each pass, you can count passes without tracing. Assuming the limit L is at least the start s: starting at s, the loop i < L runs L − s times, and the loop i <= L runs L − s + 1 times. Try the rule on four loops before you check it.

Predict

The program below sets i to a start value and runs a while loop four times, each time counting the passes. How many passes does each loop make? Use the rule, then confirm at least one with a trace table.

code/m04-loops/predict/PassCounts.java
public class PassCounts {
    public static void main(String[] args) {
        int a = 0;
        int i = 0;
        while (i < 5) { a++; i++; }

        int b = 0;
        i = 1;
        while (i < 5) { b++; i++; }

        int c = 0;
        i = 1;
        while (i <= 5) { c++; i++; }

        int d = 0;
        i = 5;
        while (i < 5) { d++; i++; }

        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println("d = " + d);
    }
}
Reveal the answer
Terminal, in code/m04-loops/predict
> javac PassCounts.java
> java PassCounts
a = 5
b = 4
c = 5
d = 0

Loop a starts at 0 and stops before 5: values 0, 1, 2, 3, 4, which is 5 passes (5 − 0). Loop b starts at 1 and stops before 5: values 1, 2, 3, 4, which is 4 passes (5 − 1). Loop c uses <=, so it includes 5: values 1 to 5, which is 5 passes (5 − 1 + 1). Loop d starts at 5, the test 5 < 5 is false at once, and the body runs 0 times. Zero passes is allowed.

Which form should you choose? Say aloud which values the body needs. If the body needs 1, 2, …, 10, write i = 1 and i <= 10: the code then reads like the sentence. If the body needs n repetitions and does not care what the counter is, i = 0 and i < n is a form you will see very often in Java code, because n − 0 is the number of passes with no adjustment. Either is correct. What matters is that you decide, and that you test the smallest case in your head: with a limit of 1, or of 0, does the loop do what you meant?

The for loop

Every counting loop in the last two sections has the same three parts spread over three places: the start before the loop, the test in the first line of the loop, and the update at the bottom of the body. It is easy to forget one of them. The for loop gathers all three into a single line:

for (initialisation; condition; update) {
    body
}

It is not a new kind of loop. It is a while loop with a tidier layout, and the three parts map one to one. The layouts differ in two small ways, scope and the effect of continue, which are covered below and in the section break and continue.

Part of the for headerWhen it runsIn the equivalent while
initialisation, int i = 1once, before anything elsethe statement before the loop
condition, i <= 5before every pass, including the firstthe condition in the parentheses
update, i++after the body, on every passthe last statement of the body (but see continue, later)

The next program computes the sum of 1 to 5 both ways, so that you can see the correspondence in the code:

code/m04-loops/ForVsWhile.java
// The same sum written as a for loop and as a while loop.
public class ForVsWhile {
    public static void main(String[] args) {
        int forTotal = 0;
        for (int i = 1; i <= 5; i++) {
            forTotal = forTotal + i;
        }
        System.out.println("for:   " + forTotal);

        int whileTotal = 0;
        int j = 1;
        while (j <= 5) {
            whileTotal = whileTotal + j;
            j++;
        }
        System.out.println("while: " + whileTotal);
    }
}
Terminal, in code/m04-loops
> javac ForVsWhile.java
> java ForVsWhile
for:   15
while: 15

The for loop on lines 5 to 7 and the while version on lines 11 to 15 (the start on line 11, the loop on lines 12 to 15) do the same work, with the same three parts in different places. The order of events in a for loop is the same as in the while:

1. initialise runs once 2. condition true or false? true 3. the body runs once 4. update for example i++ then back to step 2 false after the loop

The scope of the loop variable

Of the two differences between the layouts, scope matters straight away. A variable declared in the initialisation part exists only for the loop: in the header and in the body, and nowhere else. This is the scope rule from lesson 3, applied to the loop. The i in ForVsWhile stops existing at the closing brace on line 7, while j, declared in an ordinary statement, is still in scope on line 16. Try to use the loop's variable after the loop and the compiler refuses:

code/m04-loops/broken/ForScope.java
public class ForScope {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("i = " + i);
        }
        System.out.println("After the loop, i is " + i);
    }
}
Terminal, in code/m04-loops/broken
> javac ForScope.java
ForScope.java:6: error: cannot find symbol
        System.out.println("After the loop, i is " + i);
                                                     ^
  symbol:   variable i
  location: class ForScope
1 error

This is the cannot find symbol error from lesson 1, with a variable this time: the compiler looked for a name i where line 6 is, and none is in scope. Scope is also why you can write several for loops one after another that each declare their own i, as the next example does three times.

Counting down and stepping by more than one

The three parts can be anything that fits their job. To count down, start high, test with >= or >, and update with i--. To step by more than one, use i += 2 or similar in the update.

code/m04-loops/ForSteps.java
// Counting down, and stepping by more than one.
public class ForSteps {
    public static void main(String[] args) {
        System.out.print("Down:");
        for (int i = 5; i >= 1; i--) {
            System.out.print(" " + i);
        }
        System.out.println();

        System.out.print("Evens:");
        for (int i = 0; i <= 10; i += 2) {
            System.out.print(" " + i);
        }
        System.out.println();

        System.out.print("Threes:");
        for (int i = 1; i <= 10; i += 3) {
            System.out.print(" " + i);
        }
        System.out.println();
    }
}
Terminal, in code/m04-loops
> javac ForSteps.java
> java ForSteps
Down: 5 4 3 2 1
Evens: 0 2 4 6 8 10
Threes: 1 4 7 10

The third loop is the one to trace. Its values are 1, 4, 7, 10, and then 13, at which the test 13 <= 10 fails. Here 10 happens to be hit exactly. With a start of 2 the values would be 2, 5, 8, and 11 would fail the test, so the last value printed would be 8. A loop stops when the variable first goes beyond the limit, not when it reaches it.

The variable also keeps its last value when you declare it before the loop and leave the initialisation as a plain assignment (i = 10, without int). That is rarely what you want, but it shows exactly where the loop stops.

Predict

Trace this loop on paper, and write down every line it prints. In particular, what is i on the very last line?

code/m04-loops/predict/ForEnd.java
public class ForEnd {
    public static void main(String[] args) {
        int i;
        for (i = 10; i < 25; i += 4) {
            System.out.println("in loop: i = " + i);
        }
        System.out.println("after loop: i = " + i);
    }
}
Reveal the answer
passi at starti < 25i after the update
110true14
214true18
318true22
422true26
check26false
Terminal, in code/m04-loops/predict
> javac ForEnd.java
> java ForEnd
in loop: i = 10
in loop: i = 14
in loop: i = 18
in loop: i = 22
after loop: i = 26

Four passes, printing 10, 14, 18 and 22. The last line shows 26, the first value that made the condition false. The update runs after the last pass just as it does after every other, so the variable ends up one step beyond the last value the body saw.

The do-while loop

Both loops so far test before the body. The third kind tests after it:

do {
    body
} while (condition);

The body runs first, then the condition is checked, and if it is true the loop goes round again. The consequence is that a do-while body runs at least once, whatever the condition says. Note the semicolon after the closing parenthesis: it is required.

The difference shows up in a task where the starting value can already be the stopping value. Counting the digits of a whole number means dividing by 10 until nothing is left. What about the number 0? It has one digit, but the while version below thinks it has none.

code/m04-loops/DigitCount.java
// Counts the digits of a whole number by dividing by 10 until nothing is left.
// Try it with number = 0: the two loops disagree.
public class DigitCount {
    public static void main(String[] args) {
        int number = 0;

        int left = number;
        int digits = 0;
        while (left != 0) {
            digits++;
            left /= 10;
        }
        System.out.println("while:    digits = " + digits);

        left = number;
        digits = 0;
        do {
            digits++;
            left /= 10;
        } while (left != 0);
        System.out.println("do-while: digits = " + digits);
    }
}
Terminal, in code/m04-loops
> javac DigitCount.java
> java DigitCount
while:    digits = 0
do-while: digits = 1

Trace each loop for number = 0. In the while loop, left != 0 is false at the very first check, so the body never runs and digits stays 0. In the do-while loop the body runs once whatever happens: digits becomes 1, left becomes 0, then the check left != 0 is false and the loop ends. For any number other than 0 both loops count the same.

That is the test for choosing it: does this job need one pass before there is anything to test? A common example is asking the user for an answer and asking again until it is acceptable. You cannot test an answer you have not yet asked for. Programs cannot read keyboard input yet; keyboard input is introduced in lesson 8, and do-while will fit it well.

Predict

Trace this program. What does it print, and how many times does the body run?

code/m04-loops/predict/DoWhileOnce.java
public class DoWhileOnce {
    public static void main(String[] args) {
        int n = 5;
        do {
            n = n + 1;
            System.out.println("n is " + n);
        } while (n < 3);
        System.out.println("done, n = " + n);
    }
}
Reveal the answer
Terminal, in code/m04-loops/predict
> javac DoWhileOnce.java
> java DoWhileOnce
n is 6
done, n = 6

The body runs once. n becomes 6, n is 6 is printed, and only then is 6 < 3 checked. It is false, so the loop ends. A while loop with the same condition and the same starting value would have printed nothing at all.

A semicolon is easy to forget in a do-while. The compiler tells you plainly:

code/m04-loops/broken/DoWhileNoSemicolon.java
public class DoWhileNoSemicolon {
    public static void main(String[] args) {
        int n = 0;
        do {
            n++;
        } while (n < 3)
        System.out.println("n is " + n);
    }
}
Terminal, in code/m04-loops/broken
> javac DoWhileNoSemicolon.java
DoWhileNoSemicolon.java:6: error: ';' expected
        } while (n < 3)
                       ^
1 error

break and continue

Two statements let you interrupt a pass. You use them inside loops. (break also ends a case in a classic switch, as you saw in lesson 3.)

break: stop when you have the answer

This program looks for the first number from 1 upwards that is a multiple of both 4 and 6:

code/m04-loops/FirstMatch.java
// break: leave the loop as soon as the answer is found.
public class FirstMatch {
    public static void main(String[] args) {
        int n = 1;
        while (n <= 100) {
            if (n % 4 == 0 && n % 6 == 0) {
                System.out.println("First multiple of both 4 and 6: " + n);
                break;
            }
            n++;
        }
        System.out.println("The loop ended with n = " + n);
    }
}
Terminal, in code/m04-loops
> javac FirstMatch.java
> java FirstMatch
First multiple of both 4 and 6: 12
The loop ended with n = 12
nn % 4 == 0n % 6 == 0both?what happens
1 to 3falsefalsefalsen++
4truefalsefalsen++
5falsefalsefalsen++
6falsetruefalsen++
7falsefalsefalsen++
8truefalsefalsen++
9 to 11falsefalsefalsen++
12truetruetrueprint, then break: n++ is skipped

At break, the loop ends in the middle of a pass. That is why n is still 12 afterwards: the update at the bottom of the body never ran for that pass. Without break the program would carry on testing 13, 14, and so on up to 100, long after the answer was known.

You can get the same behaviour without break, by adding a boolean variable that the condition also tests:

code/m04-loops/FlagVersion.java
// The same search as FirstMatch, written without break. A boolean flag ends the loop.
public class FlagVersion {
    public static void main(String[] args) {
        int n = 1;
        boolean found = false;
        while (n <= 100 && !found) {
            if (n % 4 == 0 && n % 6 == 0) {
                System.out.println("First multiple of both 4 and 6: " + n);
                found = true;
            } else {
                n++;
            }
        }
        System.out.println("The loop ended with n = " + n);
    }
}
Terminal, in code/m04-loops
> javac FlagVersion.java
> java FlagVersion
First multiple of both 4 and 6: 12
The loop ended with n = 12

The output is identical. Neither version is always better. The break version is shorter and says stop here exactly where the discovery happens. The flag version says in its header every reason the loop might end (n <= 100 or found), so a reader never has to look inside the body to learn when the loop stops.

continue: skip this one

code/m04-loops/SkipThrees.java
// continue: abandon this pass and go on to the next one.
public class SkipThrees {
    public static void main(String[] args) {
        System.out.print("Kept:");
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue;
            }
            System.out.print(" " + i);
        }
        System.out.println();
    }
}
Terminal, in code/m04-loops
> javac SkipThrees.java
> java SkipThrees
Kept: 1 2 4 5 7 8 10
i at starti % 3 == 0what happens
1falseprints 1; update gives 2
2falseprints 2; update gives 3
3truecontinue: nothing printed; the update still runs, giving 4
4falseprints 4; update gives 5
5, 7, 8, 10falseprinted
6, 9truecontinue: skipped
checkafter 10 the update gives 11, and 11 <= 10 is false

A for loop is safe with continue because the update is in the header, so skipping the rest of the body cannot skip it. A while loop keeps its update inside the body, and continue jumps over everything after it, update included:

code/m04-loops/ContinueTrap.java
// In a while loop, continue skips the rest of the body, including the update.
// The safety counter is the only reason this program ends.
public class ContinueTrap {
    public static void main(String[] args) {
        int i = 0;
        int passes = 0;
        while (i < 6 && passes < 8) {
            passes++;
            if (i == 2) {
                continue;      // jumps to the condition; i++ below is skipped
            }
            System.out.println("i = " + i);
            i++;
        }
        System.out.println("Stopped with i = " + i + " after " + passes + " passes");
    }
}
Terminal, in code/m04-loops
> javac ContinueTrap.java
> java ContinueTrap
i = 0
i = 1
Stopped with i = 2 after 8 passes

Trace it: on the third pass i is 2, the if is true, continue sends the program back to the condition, and i++ on line 13 is never reached. i is 2 on every pass after that, so every later pass does the same, and only the safety counter ends the loop. Without it this would be an infinite loop that prints nothing more after i = 1.

When they help, and when they hide the logic

Neither break nor continue is required: any loop can be written without them. They earn their place when they remove awkward nesting or a flag variable, as in the search above. They do harm when a body has several of them, because then the loop has several ways to end and each pass can stop at several places, and tracing it becomes hard. A good test: can you say in one sentence when the loop ends? If the honest answer is when the condition fails, or when the first break fires, or when the second one does, the structure should probably be rewritten.

Predict

This loop has both. Trace it and write down what it prints. Which values of i reach continue, and which reach break?

code/m04-loops/predict/MixedLoop.java
public class MixedLoop {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;
            }
            if (i > 7) {
                break;
            }
            System.out.println("i = " + i);
        }
        System.out.println("done");
    }
}
Reveal the answer
ii % 2 == 0i > 7what happens
1falsefalseprints 1
2truecontinue
3falsefalseprints 3
4truecontinue
5falsefalseprints 5
6truecontinue
7falsefalseprints 7
8truecontinue
9falsetruebreak
Terminal, in code/m04-loops/predict
> javac MixedLoop.java
> java MixedLoop
i = 1
i = 3
i = 5
i = 7
done

Even values are skipped by continue before the second test is reached. The first odd value above 7 is 9, which triggers break, so 9 is never printed and 10 is never examined. Execution continues at the line after the loop, which prints done.

Nested loops

The body of a loop can contain any statements, including another loop. A loop inside a loop is a nested loop. The inner loop is part of one pass of the outer one, so it runs from start to finish, afresh, on every pass of the outer loop. The natural picture is a grid: the outer loop counts rows, the inner loop counts the columns in one row.

code/m04-loops/Rectangle.java
// Nested loops: the outer loop counts rows, the inner loop counts columns.
public class Rectangle {
    public static void main(String[] args) {
        int rows = 2;
        int cols = 3;
        for (int row = 1; row <= rows; row++) {
            for (int col = 1; col <= cols; col++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Terminal, in code/m04-loops
> javac Rectangle.java
> java Rectangle
***
***

Three details make the picture work. The inner loop uses print, so its stars land side by side on one line. The single println() after the inner loop, still inside the outer body, ends the line once the row is complete. And the inner loop variable col starts again at 1 for every row, because its declaration is part of the inner for, which runs anew on each outer pass. The trace shows that restart:

rowcolcol <= 3what happens
11trueprint *
12trueprint *
13trueprint *
14falseinner loop ends; println() ends the line
21trueprint * (col starts again at 1)
22trueprint *
23trueprint *
24falseinner loop ends; println() ends the line
3outer check 3 <= 2 is false: the outer loop ends

The two loops need different variable names. If the inner loop declares row again while the outer row is still in scope, the compiler objects:

code/m04-loops/broken/SameName.java
public class SameName {
    public static void main(String[] args) {
        for (int row = 1; row <= 2; row++) {
            for (int row = 1; row <= 3; row++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Terminal, in code/m04-loops/broken
> javac SameName.java
SameName.java:4: error: variable row is already defined in method main(String[])
            for (int row = 1; row <= 3; row++) {
                     ^
1 error

When the inner loop depends on the outer one

The inner loop's limit can use the outer variable. Making each row as long as its row number draws a triangle:

code/m04-loops/Triangle.java
// The inner loop's limit depends on the outer loop's variable.
public class Triangle {
    public static void main(String[] args) {
        int height = 4;
        for (int row = 1; row <= height; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Terminal, in code/m04-loops
> javac Triangle.java
> java Triangle
*
**
***
****
rowinner loop runs col =printed
11*
21, 2**
31, 2, 3***
41, 2, 3, 4****

Counting the passes

The body of the inner loop runs once per pass of the inner loop, per pass of the outer loop. When the inner loop always makes the same number of passes, the counts multiply: 4 rows of 6 columns means 4 × 6 = 24 passes. When it varies, you add up the inner counts row by row: the triangle makes 1 + 2 + 3 + 4 = 10. This is worth knowing before you write a nested loop over large ranges, because the work grows very quickly. Two loops of 1,000 passes each already mean a million passes of the inner body.

code/m04-loops/Passes.java
// Counts how many times an inner loop body runs in total.
public class Passes {
    public static void main(String[] args) {
        int rectangle = 0;
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= 6; col++) {
                rectangle++;
            }
        }
        System.out.println("Rectangle 4 by 6: " + rectangle + " passes");

        int triangle = 0;
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                triangle++;
            }
        }
        System.out.println("Triangle of height 4: " + triangle + " passes");
    }
}
Terminal, in code/m04-loops
> javac Passes.java
> java Passes
Rectangle 4 by 6: 24 passes
Triangle of height 4: 10 passes

One more fact to keep straight. break leaves only the loop it is written in. In a nested loop that means the inner one; the outer loop carries on.

code/m04-loops/InnerBreak.java
// break leaves only the loop it is written in: here, the inner one.
public class InnerBreak {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 5; col++) {
                if (col == 3) {
                    break;
                }
                System.out.print(col);
            }
            System.out.println();
        }
    }
}
Terminal, in code/m04-loops
> javac InnerBreak.java
> java InnerBreak
12
12
12

Each row stops at col == 3 and prints only 12, but all three rows are still printed, because the outer loop was never interrupted.

Predict

Draw a trace table with columns row, col, col == row and what is printed. Then write down the picture this program draws.

code/m04-loops/predict/Diagonal.java
public class Diagonal {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 3; col++) {
                if (col == row) {
                    System.out.print("X");
                } else {
                    System.out.print("-");
                }
            }
            System.out.println();
        }
    }
}
Reveal the answer
Terminal, in code/m04-loops/predict
> javac Diagonal.java
> java Diagonal
X--
-X-
--X

The if inside the inner loop prints X only on the pass where the column number equals the row number: column 1 of row 1, column 2 of row 2, column 3 of row 3. Every other cell gets -. The inner loop has 3 passes per row and there are 3 rows, so 9 characters are printed, plus 3 line ends.

Building up a result across passes

Sums and counts are numbers that grow. A loop can also grow a String, using += to add a piece to the end on each pass. This program builds the text 1+2+3+4+5 and the total at the same time:

code/m04-loops/BuildText.java
// Building a text and a total together, one piece per pass.
public class BuildText {
    public static void main(String[] args) {
        String text = "";
        int total = 0;
        for (int i = 1; i <= 5; i++) {
            if (i > 1) {
                text += "+";       // a separator goes between pieces, not before the first
            }
            text += i;
            total += i;
            System.out.println("after pass " + i + ": text = " + text + ", total = " + total);
        }
        System.out.println(text + " = " + total);
    }
}
Terminal, in code/m04-loops
> javac BuildText.java
> java BuildText
after pass 1: text = 1, total = 1
after pass 2: text = 1+2, total = 3
after pass 3: text = 1+2+3, total = 6
after pass 4: text = 1+2+3+4, total = 10
after pass 5: text = 1+2+3+4+5, total = 15
1+2+3+4+5 = 15

Start from an empty text, "", in the same way that a sum starts from 0. The program prints its own trace: after each pass the text has one more piece and the total has grown by the same number. Two details are worth studying.

Each += on a text creates a new, longer text rather than extending the old one. For short texts like this that does not matter. Lesson 6 introduces a tool designed for building long texts piece by piece.

Mistakes loops produce

Some of these you have met already: the missing update, the off-by-one, the scope error and the missing do-while semicolon. Here are four more, each with its real behaviour.

A semicolon after the header

code/m04-loops/SemicolonFor.java
// The semicolon after the for header is a complete, empty body.
public class SemicolonFor {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++);
        {
            System.out.println("Hello");
        }
    }
}
Terminal, in code/m04-loops
> javac SemicolonFor.java
> java SemicolonFor
Hello

The program compiles without any message and prints Hello once, not three times. A lone ; is a complete statement that does nothing, so for (...); is a loop whose body is empty. It makes three empty passes. The braces on the next lines are then an ordinary block that runs once, after the loop. The compiler cannot tell this from what you meant, because both are legal.

The same slip after a while header is worse. In while (n < 3); the body is empty, so nothing in it can change n. If the condition is true the first time, it is true on every later check, and the program freezes at that loop. If you meet a program that hangs, look for a ; at the end of a loop header, then press Ctrl+C.

Changing the loop variable inside a for body

code/m04-loops/TouchingCounter.java
// The body changes the loop variable as well as the header doing so.
public class TouchingCounter {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("i = " + i);
            i++;
        }
    }
}
Terminal, in code/m04-loops
> javac TouchingCounter.java
> java TouchingCounter
i = 1
i = 3
i = 5
i = 7
i = 9

The header says i++ and so does the body, so i goes up by 2 on every pass, and half of the intended values are skipped. The compiler allows it, because the loop variable is an ordinary variable. It is rarely intended. A for header should tell the whole story of how the variable moves; when the body also moves it, a reader has to trace the loop to learn what it does. If the variable has to move by irregular amounts, that is a sign the loop should be a while, where the update is visible in the body.

A double counter that misses its end value

Lesson 2 showed that double values are only approximately right: 0.1 cannot be stored exactly. A loop that adds 0.1 repeatedly and tests with != for 1.0 collects the small errors on every pass.

code/m04-loops/DoubleCounter.java
// A double counter that is compared with != 1.0. The safety counter ends the run.
public class DoubleCounter {
    public static void main(String[] args) {
        int passes = 0;
        for (double x = 0.0; x != 1.0 && passes < 13; x += 0.1) {
            passes++;
            System.out.println("pass " + passes + ": x = " + x);
        }
    }
}
Terminal, in code/m04-loops
> javac DoubleCounter.java
> java DoubleCounter
pass 1: x = 0.0
pass 2: x = 0.1
pass 3: x = 0.2
pass 4: x = 0.30000000000000004
pass 5: x = 0.4
pass 6: x = 0.5
pass 7: x = 0.6
pass 8: x = 0.7
pass 9: x = 0.7999999999999999
pass 10: x = 0.8999999999999999
pass 11: x = 0.9999999999999999
pass 12: x = 1.0999999999999999
pass 13: x = 1.2

The variable never equals 1.0 exactly: it reaches 0.9999999999999999 on pass 11 and goes straight past. The safety counter ended this run on pass 13; without it the test x != 1.0 would be true on every check, which is the StepsOver problem again. Changing the test to x < 1.0 stops the infinite loop, but is the count right? Suppose the task is to run for x = 0.0, 0.1, …, 0.9, up to but not including 1.0. That should be ten passes. Here it is written with a double counter and with an int counter:

code/m04-loops/DoubleFixed.java
// Task: run for x = 0.0, 0.1, ..., 0.9, up to but not including 1.0. That is ten passes.
public class DoubleFixed {
    public static void main(String[] args) {
        int passes = 0;
        double last = 0.0;
        for (double x = 0.0; x < 1.0; x += 0.1) {
            passes++;
            last = x;
        }
        System.out.println("double counter: " + passes + " passes, last x = " + last);

        passes = 0;
        for (int step = 0; step < 10; step++) {
            double x = step / 10.0;
            passes++;
            last = x;
        }
        System.out.println("int counter:    " + passes + " passes, last x = " + last);
    }
}
Terminal, in code/m04-loops
> javac DoubleFixed.java
> java DoubleFixed
double counter: 11 passes, last x = 0.9999999999999999
int counter:    10 passes, last x = 0.9

The double loop makes 11 passes, not 10, and its last x is 0.9999999999999999. Adding 0.1 ten times does not give exactly 1.0 (it gives 0.9999999999999999), so the test x < 1.0 is still true and one pass too many runs. Nothing warns you: the program compiles, runs and prints. The int loop makes the ten passes that were asked for, and its last x is 0.9.

The error can fall the other way as well. This loop is meant to run for 0.0, 0.1, 0.2 and 0.3, which is four passes:

code/m04-loops/DoubleShort.java
// Task: run for x = 0.0, 0.1, 0.2 and 0.3. That is four passes.
public class DoubleShort {
    public static void main(String[] args) {
        int passes = 0;
        double last = 0.0;
        for (double x = 0.0; x <= 0.3; x += 0.1) {
            passes++;
            last = x;
        }
        System.out.println("double counter: " + passes + " passes, last x = " + last);
    }
}
Terminal, in code/m04-loops
> javac DoubleShort.java
> java DoubleShort
double counter: 3 passes, last x = 0.2

It makes three. Lesson 2 showed that 0.1 + 0.2 is 0.30000000000000004, which is already more than 0.3, so the test x <= 0.3 fails one pass early. One loop ran too often and the other not often enough, and neither gave any sign of it.

The reliable way is to let an int do the counting and calculate the double from it, as the second loop of DoubleFixed does. Integers count without any error, so the loop makes the number of passes you wrote. As a rule: count with integers, and compute doubles from the counter.

A running product that overflows

The product pattern grows quickly. Factorials (1, 1×2, 1×2×3, …) show how quickly, and show lesson 2's int overflow happening inside a loop:

code/m04-loops/FactorialInt.java
// A running product in an int. Watch what happens after 12!.
public class FactorialInt {
    public static void main(String[] args) {
        int factorial = 1;
        for (int n = 1; n <= 15; n++) {
            factorial = factorial * n;
            System.out.println(n + "! = " + factorial);
        }
    }
}
Terminal, in code/m04-loops
> javac FactorialInt.java
> java FactorialInt
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 1932053504
14! = 1278945280
15! = 2004310016

12! is correct. 13! should be 6,227,020,800, which does not fit in an int, so the value wraps round and the program prints 1932053504, with no error and no warning. Every figure after that is wrong too. A long holds bigger numbers, and it pushes the limit further, though not to infinity:

code/m04-loops/FactorialLong.java
// The same running product in a long. It lasts longer, but it also overflows.
public class FactorialLong {
    public static void main(String[] args) {
        long factorial = 1;
        for (int n = 1; n <= 22; n++) {
            factorial = factorial * n;
            System.out.println(n + "! = " + factorial);
        }
    }
}
Terminal, in code/m04-loops
> javac FactorialLong.java
> java FactorialLong
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = -4249290049419214848
22! = -1250660718674968576

The long is correct up to 20! and wraps at 21!, which it shows as a negative number. A negative factorial is the giveaway here, but wrapping does not always produce an obviously wrong answer. When a loop multiplies, or adds up a lot, ask how big the result can get, and pick the type for that size. Java will not tell you if you picked wrongly.

Symptoms and likely causes

What you seeLook for
The program never stops, or the same line scrolls byno update, an update that moves the wrong way, a != test that is stepped over, or a continue before the update in a while
The program hangs at a loop and prints nothing morea ; after a while header
The answer is slightly wrong: one too small, or one too big< instead of <=, or the wrong starting value
The body ran once instead of many timesa ; after a for header
The loop skips valuesthe variable is changed in the header and again in the body
cannot find symbol on a loop variableusing it after the loop that declared it
A big number turns negative or wrongint overflow in a running total or product
A double loop makes one pass too many (or too few), for example 11 passes instead of 10a double loop variable; count with an int

Choosing a loop

LoopUse it whenExample in this lesson
foryou know how many passes there will be, or the loop is a count from one value to anotherForSteps, Triangle, BuildText
whilethe number of passes depends on something the body changes, and zero passes is possibleHalve, FirstMatch, digits of a number
do-whilethere must be at least one pass before the first test makes senseDigitCount for 0

The choice is mostly about readability: any of the three can do the work of any other. for puts the start, test and update where a reader can see them together; use it when the loop is a count. while suits a loop whose end is a condition about the data, such as until the number has been halved down to 1. do-while is the least common, and it is the right tool when a first pass is needed. (Java also has a second form of for, the for-each loop, which visits every item of a collection. It is left to lesson 7, because it needs arrays.)

Exercises

Each exercise has a folder waiting in work/m04-loops/ in your course kit. Compile and run from the terminal, inside the exercise's folder. In every exercise, trace on paper before you ask the computer; the traces are the point.

warm-up

Exercise 4.1 · Trace first

Work in work/m04-loops/ex1-trace-first/ in your course kit

Your folder contains Mystery.java and a notes file, trace.md. Do not compile or run the program yet.

work/m04-loops/ex1-trace-first/Mystery.java
// Do NOT compile or run this until you have filled in Parts 1 and 2 of trace.md.
public class Mystery {
    public static void main(String[] args) {
        int a = 2;
        int b = 20;
        int steps = 0;
        while (a < b) {
            a = a * 2;
            b = b - 3;
            steps++;
        }
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("steps = " + steps);
    }
}
  1. Fill in the trace table in trace.md, one row per pass, and write the three lines you expect it to print.
  2. Answer in trace.md: how many times is the condition a < b evaluated in total, and how many of those evaluations are true?
  3. Only now compile and run. Paste the real output into trace.md and say whether your prediction matched. If it did not, find the first row of your table that was wrong.
  4. Change int b = 20; to int b = 40;. Draw a second trace table and predict the output before running it, then run it and check.

Leave the program at int b = 20; when you finish. The real output is hidden here so that you can try first:

Real output of the unchanged program (open it only after your prediction is written)
Terminal
a = 16
b = 11
steps = 3
Hint

Each pass changes both a and b, and the condition looks at both. In the row for pass 2, the values in the at start columns are the values in the after columns of the row before.

To check it, run python check.py m04 ex1 in your course kit folder.

warm-up

Exercise 4.2 · Digit sum

Work in work/m04-loops/ex2-digit-sum/ in your course kit

Write DigitSum.java (class DigitSum). It starts with int number = 9075314; and prints the sum of the number's digits, and how many digits it has, using a while loop. No text conversion is allowed: use only % and /.

  • The original number must still be printed at the end, so the loop has to work on a copy.
  • Changing the first line to another positive whole number must give correct results.
Required output of java DigitSum
Number: 9075314
Digit sum: 29
Number of digits: 7
Hint 1

Think about what number % 10 gives you, and what number / 10 gives you. Together they take a digit off the end and leave the rest.

Hint 2

Trace the loop for the number 507 by hand before writing any code. Write a column for the number that is left, one for the digit sum so far and one for the digit count so far.

To check it, run python check.py m04 ex2 in your course kit folder.

core

Exercise 4.3 · Collatz steps

Work in work/m04-loops/ex3-collatz/ in your course kit

Pick any positive whole number and repeat this rule until you reach 1: if the number is even, halve it; if it is odd, multiply it by 3 and add 1. Nobody has proved that every starting number reaches 1, although it has been checked for an enormous range of them. The question is how many steps it takes. For a start of 6 the numbers are 6, 3, 10, 5, 16, 8, 4, 2, 1: that is 8 steps, and the highest value reached is 16.

Write Collatz.java (class Collatz) with int start = 27; that counts the steps and also finds the highest value reached along the way (including the start itself), using one while loop.

  • The variable start must keep its value; the loop works on a copy.
  • The program must work for other starting values, so do not hard-code any answer.
Required output of java Collatz
Start: 27
Steps to reach 1: 111
Highest value: 9232
Hint 1

Two of the patterns from the section Four patterns you will use constantly are running at once: one variable counts the passes, and one tracks the largest value so far.

Hint 2

Test your program with a start of 6 before you try 27. You know the correct answers for 6 already. Also ask yourself where in the body the comparison with the highest value belongs.

To check it, run python check.py m04 ex3 in your course kit folder.

core

Exercise 4.4 · Times table

Work in work/m04-loops/ex4-times-table/ in your course kit

Write TimesTable.java (class TimesTable) that prints a 6 by 6 multiplication table with a header row and a label column, using for loops and tab characters, with every line exactly as shown. Each gap is a single tab (\t), and no line has anything after its last number, not even a space or a tab.

Required output of java TimesTable
x	1	2	3	4	5	6
1	1	2	3	4	5	6
2	2	4	6	8	10	12
3	3	6	9	12	15	18
4	4	8	12	16	20	24
5	5	10	15	20	25	30
6	6	12	18	24	30	36
  • The size 6 must appear once in your program, as a variable int size = 6;. Every loop must use it, so that changing it to 4 gives a correct 4 by 4 table.
  • The header row comes from a single loop. The six rows below it come from two nested loops. No product may be typed in as a literal.
Hint 1

Print each row with print calls, then one println(). The question is where in the loop each tab goes: before each number or after each. One of the two leaves a tab at the end of the line.

Hint 2

Trace the first two rows, writing for each pass of the inner loop what is printed. The label at the start of a row is printed by the outer loop, before the inner loop begins.

To check it, run python check.py m04 ex4 in your course kit folder.

core

Exercise 4.5 · Loop bug log

Work in work/m04-loops/ex5-loop-bug-log/ in your course kit

Your folder contains BugLoops.java, which has three loops. Each has one mistake, and the comment above each loop says what it should do. You also have bug-log.md.

work/m04-loops/ex5-loop-bug-log/BugLoops.java
// Three loops, one mistake in each. The comment above each loop says what it should do.
public class BugLoops {
    public static void main(String[] args) {
        // Part 1: add 1 + 2 + ... + 10
        int total = 0;
        for (int i = 1; i < 10; i++) {
            total += i;
        }
        System.out.println("Sum of 1 to 10 is " + total);

        // Part 2: print "Beep" three times
        for (int i = 1; i <= 3; i++);
        {
            System.out.println("Beep");
        }

        // Part 3: count down from 10 to 2 in steps of 2, one number per line
        int n = 10;
        while (n >= 2) {
            System.out.println(n);
            n--;
        }
        System.out.println("Done");
    }
}
  1. Compile and run the program as it is. Paste its output into the log.
  2. For each of the three bugs, write in the log: where it is, the first rows of a trace table for the faulty loop, a sentence or two saying why the loop does what it does, and what you changed.
  3. Fix all three so that the program prints the output below. Change as little as you can.
  4. Answer the question at the end of the log: why does the compiler accept the bug in Part 2?
Output of the fixed program
Sum of 1 to 10 is 55
Beep
Beep
Beep
10
8
6
4
2
Done
Hint 1

Compare what the unfixed program printed with the output above. Each of the three differences points at one of the bugs. Then trace the faulty loop: the trace shows what the loop actually does, which is not always what the header suggests.

Hint 2

For the question about Part 2, reread the section Mistakes loops produce and ask what a lone ; means to the compiler.

To check it, run python check.py m04 ex5 in your course kit folder.

stretch

Exercise 4.6 · Prime hunt

Work in work/m04-loops/ex6-prime-hunt/ in your course kit

A whole number above 1 is prime if no whole number from 2 up to one less than itself divides it with no remainder. Write PrimeHunt.java (class PrimeHunt) with int limit = 50; that finds every prime up to the limit using nested loops, and reports how much work it did.

  • The outer loop takes each candidate from 2 up to the limit.
  • The inner loop tries divisors d = 2, 3, 4, … for as long as d * d <= candidate. It must stop with break as soon as it finds a divisor. (Stopping at d * d <= candidate is safe because if candidate equals a × b with a no bigger than b, then a × a is no bigger than candidate. So any number that has a divisor has a smaller one that the loop reaches before d * d passes candidate.)
  • Count one division tried each time the program evaluates candidate % d.
  • Build the first output line as a single String with +=, starting from "Primes up to " + limit + ":" and adding " " + candidate for each prime. There must be no space at the end of the line.
Required output of java PrimeHunt
Primes up to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Primes found: 15
Divisions tried: 95

Then complete answers.md. Before you try it, predict what happens to each of the three output lines if you delete the break; statement and change nothing else, and explain why. Then delete it, run the program, record what you saw, and put the break; back.

Hint 1

Each candidate needs a fresh start: a boolean that says no divisor found yet, set to true at the top of the outer loop body, not before the outer loop. The inner loop sets it to false when it finds a divisor.

Hint 2

Trace the candidates 4, 7 and 9 through the inner loop on paper, including the check that ends it. Count the divisions tried for each, and work out why the inner loop ends for each of them.

To check it, run python check.py m04 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
LoopA statement that runs a block of statements repeatedly.
Pass (iteration)One run of a loop's body.
ConditionThe boolean expression that decides whether a loop runs another pass.
BodyThe block of statements a loop repeats.
Loop variableThe variable the condition examines and the body or header changes.
UpdateThe step that changes the loop variable towards the end of the loop.
Infinite loopA loop whose condition never becomes false.
Trace (trace table)Working through a program by hand, recording every variable per pass.
AccumulatorA variable that collects a result across passes, such as a total.
Off-by-one errorA loop that runs one pass too many or too few.
for loopA loop with its initialisation, condition and update in the header.
do-while loopA loop that tests its condition after the body, so the body runs at least once.
breakEnds the innermost loop immediately.
continueEnds the current pass and goes on to the next.
Nested loopA loop inside the body of another loop.