Computer Fundamentals and Introduction to Programming · Lecture Notes
Chapter 8: Loops
The real power of a computer comes from its ability to do the same job thousands of times without getting tired. In a program, loops provide this repetition. This chapter first introduces the four parts found in every loop: initialization, condition, body, and update. Then come Java's three loops: for, while, and do-while. Each is traced iteration by iteration with a small program. The break and continue statements, which change the flow of a loop, and typical mistakes such as infinite loops and boundary errors are also treated in detail. The second half of the chapter is devoted to examples. Loops that work with the digits of a number, loops that search for divisors, loops that read input from the user, and patterns drawn with nested loops are gathered into a few common templates. All Java programs were compiled and run with JDK 21; the outputs given in the chapter were taken from these runs.
Learning outcomes
- Loops
- Point out the initialization, condition, body, and update parts of a loop in code; choose the one among
for,while, anddo-whilethat suits the problem; explain howbreak,continue, and labeledbreakchange the flow. - Patterns
- Compute sums, products, and counts with counters and accumulators; solve digit-count, digit-sum, reversal, and palindrome problems with the digit pattern (
% 10,/ 10); find prime and perfect numbers with the divisor pattern. - Nested loops
- Produce row-and-column layouts and star or number patterns with nested loops; find the formula that ties the number of spaces and characters in each row of a pattern to the row number.
- Tracing
- Run a loop iteration by iteration with a trace table; find mistakes such as infinite loops, boundary errors, and the
doublecounter error; test a loop with normal, zero, one, negative, and extreme values.
8.1What is a loop?
8.1.1Why do we need repetition?
Consider a program that prints the sum of the numbers from 1 to 4. A one-line solution comes to mind at once: sum = 1 + 2 + 3 + 4;. When the same job is wanted for 1 to 1000, this way does not work. Writing a line with a thousand terms is both tedious and error-prone. Moreover, the upper limit is often not known when the program is written; the user enters it while the program runs.
What these problems have in common is that the same small job is done over and over: “add one more number to the sum, then move on to the next number”. In programming languages, the construct that expresses this kind of repetition is called a loop. The programmer writes the job to be repeated once and says when to stop. The computer does the rest.
A loop is a construct that runs a group of statements over and over for as long as a condition is true. The repeated statements are called the loop body, and one run of the body is called an iteration.
Java has three loops: for, while, and do-while. All three can do the same job; the differences between them are when the condition is asked and where the parts are written. That is why we first need to get to know the parts common to every loop.
8.1.2The four parts of a loop
Every loop consists of four parts. In the slides and in this chapter, each part is always shown in the same color. Figure 8.1 gathers these parts in a general flowchart.
- Initialization: runs once before the loop and gives starting values to the variables the loop will use.
counter = 1in the figure is such a step. - Condition: a logical expression whose result is
trueorfalse. Inforandwhileloops it is asked before every iteration, and in thedo-whileloop after every iteration. If the result isfalse, the loop is left. - Body: the work done in every iteration. In the figure it is shown by the “do work” box.
- Update: changes the variable used in the condition. For example,
counter++increases the counter by 1. The job of the update is to bring the condition a little closer to its end in every iteration. If the update is forgotten, the condition always stays the same and the loop never ends.
The condition in the figure is the question counter <= n ?. counter starts at 1 and increases by 1 in every iteration. Eventually it passes n and the condition becomes false. This progress is what guarantees that the loop ends. When writing a loop, it should be clearly visible where each of the four parts is. If one of the parts is missing or wrong, the loop either does not run at all, runs one iteration too few or too many, or never ends.
A counter is a variable that changes by a fixed amount (usually 1) in every iteration and shows how many iterations have run or which element is next. An accumulator is a variable that, in every iteration, adds a new value to itself or multiplies itself by it. A sum accumulator starts from 0 and a product accumulator from 1.
The reason for the starting values is simple. 0 is the identity element of addition: adding a number to 0 gives that number. The identity element of multiplication is 1. If a product accumulator is mistakenly started at 0, every iteration multiplies by 0, so the result is always 0.
8.2The for loop
8.2.1Syntax and order of execution
When the number of repetitions is known in advance, the most suitable loop is the for loop. Three of the four parts, initialization, condition, and update, are written on the same line, inside the parentheses after the word for. The parts are separated by semicolons. The body goes between braces. The following program adds the numbers from 1 to n:
int n = 4;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println(sum);When the program runs, only the sum is printed on the screen:
10int i = 1 is the initialization, i <= n is the condition, and i++ is the update. The body is the statement sum += i.Figure 8.2 shows the flow of this program. Although the parts of a for loop are written side by side in the code, they do not run in the order in which they are written. The actual order of execution is as follows:
int i = 1runs. This step happens only once, when entering the loop.- The condition
i <= nis asked. If it is true, the body is entered; if it is false, the loop ends. - The body
sum += iruns. - The update
i++runs and the flow returns to step 2, the condition.
In short, the order is “initialization → condition → body → update → condition → body → update …”. The update is written before the body inside the parentheses but always runs after the body. This detail is very important when tracing a loop by hand.
The variable i defined in the header has one more property: it lives only inside the loop. The region of the program in which a variable can be used is called its scope. The scope of an i defined as for (int i = 1; …) is the loop itself. If System.out.println(i); is written after the loop, the compiler does not recognize i and reports an error. If the value of i is needed after the loop, i must be defined before the loop: int i; for (i = 1; i <= n; i++) ….
8.2.2Tracing a for loop step by step
The most reliable way to understand what a loop does is to run it on paper like a computer. The values that the variables take in each iteration are written in a table. This table is called a trace table. Table 8.1 is the trace table of the program above. The table was produced by running the same program with JDK 21 and printing the variables in each iteration.
| Iteration | i | i <= n | sum (after the body) |
|---|---|---|---|
| 1 | 1 | true | 1 |
| 2 | 2 | true | 3 |
| 3 | 3 | true | 6 |
| 4 | 4 | true | 10 |
| — | 5 | false | 10 (the loop ends) |
The table is read as follows. When entering the loop, int i = 1 runs. In iteration 1 the condition 1 <= 4 is true and the body makes sum = 0 + 1 = 1. Then i++ makes i 2 and the flow returns to the condition. In iteration 2, 2 <= 4 is true and sum = 1 + 2 = 3. In the same way, sum becomes 6 in iteration 3 and 10 in iteration 4. The i++ at the end of iteration 4 makes i 5. The condition 5 <= 4 is false and the loop ends. The println after the loop prints 10.
Two counts come out of the table. The body ran 4 times, and the condition was asked 5 times. The last check of the condition, the one that came out false, is also an evaluation. In general, in a for loop where i increases from 1 to n, the body runs n times and the condition runs n + 1 times. The initialization runs only once.
Defining the accumulator inside the loop. If the line int sum = 0; is moved into the body, two problems arise. First, every iteration resets the sum to 0 and the work of the earlier iterations is lost. Second, the scope of the sum is limited to the body and the println(sum) after the loop does not compile. The accumulator is always defined before the loop and gets its starting value there.
8.2.3Flexible forms of the for header
The three parts of the for header do not always have to be of the form “start at 1, increase by 1”. The counter can start from any value, increase by twos, or count backward. In the initialization part, several variables of the same type can be defined; in the update part, several expressions separated by commas can be written. Table 8.2 gives three example headers and the values they produce.
| Header | Behavior |
|---|---|
for (int i = 0, j = 9; i < j; i++, j--) | i and j move together: (0,9) (1,8) (2,7) (3,6) (4,5); 5 iterations |
for (int i = 0; i <= 10; i += 2) | 0 2 4 6 8 10 |
for (int i = 5; i >= 1; i--) | countdown: 5 4 3 2 1 |
In the first row there are two counters: i advances from the start and j from the end. In every iteration i increases by 1 and j decreases by 1. The condition i < j stops the loop when the two counters meet. After the iteration (4,5), i = 5 and j = 4; 5 < 4 is false. This pattern is often used in algorithms that move from both ends of an array toward the middle.
Each of the three parts is optional. All three can even be left empty. If the condition part is empty, Java treats it as true and the loop does not end on its own. In such a loop the exit must be provided by a break in the body:
int k = 0;
for (;;) { // all parts empty: always true
k++;
if (k == 3) break; // exit is required
}
System.out.println(k); // 3k increases by 1 in every iteration and when it reaches 3, break ends the loop. The program prints 3. That the parts can be left empty is a convenience but reduces readability. For a job with a counter, an ordinary for header with all three parts filled in is always clearer.
8.2.4i++ versus ++i
Java has two short ways of increasing a variable by 1: i++ (post-increment) and ++i (pre-increment). Both increase i by 1. The difference is in the value of the expression. The expression i++ gives the old value of i and then increases i. ++i first increases i and then gives the new value. Table 8.3 shows this difference with four small examples.
| Initially | Expression | Result | After |
|---|---|---|---|
| a = 5 | b = a++ | b = 5 | a = 6 |
| a = 5 | b = ++a | b = 6 | a = 6 |
| idx = 0 | d[idx++] | 10 | idx = 1 |
| idx = 0 | d[++idx] | 20 | idx = 1 |
In the first two rows a becomes 6 in both cases; only the value that goes to b differs. In the last two rows idx becomes 1 in both cases. d[idx++] uses the old index (0) and gives 10. d[++idx] first raises the index to 1 and gives 20.
In the update part of a for header, however, the value of the expression is not used anywhere; only its side effect, the increase of i, matters. That is why there is no difference between the following two loops:
for (int i = 0; i < 3; i++) System.out.print(i + " "); // 0 1 2
for (int i = 0; i < 3; ++i) System.out.print(i + " "); // 0 1 2Both print 0 1 2. For readability, i++, the customary form for counters, is preferred. The difference between the two forms appears only when the value of the increment expression is used inside another expression. Such nested use makes code harder to read and is a habit to avoid.
8.3The while loop
8.3.1Syntax and order of execution
The for loop offers a comfortable notation when the number of repetitions is known. In some problems, however, the number of iterations needed is not known in advance. Processing the digits of a number one by one is like that: one iteration is needed for 7 and three for 725. Asking questions until the user makes the right guess is also like that. In these cases the while loop is a more natural choice. After the word while, only the condition is written in parentheses. The initialization comes before the loop and the update is inside the body.
The while loop is a loop written as while (condition) { body } that asks the condition before every iteration. The body runs as long as the condition is true. Loops whose condition is asked before the body are called pre-test loops; the for loop is also a pre-test loop.
The following program computes the value of 5!, that is, the product 5 × 4 × 3 × 2 × 1:
int num = 5;
int factorial = 1;
while (num > 1) {
factorial *= num;
num--;
}
System.out.println(factorial);num = 5, factorial = 1) comes before the loop, and the update (num--) is at the end of the body.Figure 8.4 has the same form as the for diagram. Only the way the code is written changes: the parts gathered in the header of a for loop are spread over three separate places here. This scattering is the only risk of the while loop. The update inside the body can be forgotten. If that happens, the condition never changes and the loop never ends.
Because the condition is asked before the body, the body of a while loop may never run. If num = 1 is given in the program above, the first check 1 > 1 is false. The body is never entered and 1 is printed. This result is correct, because 1! = 1. In the same way, 1 is printed for num = 0, which agrees with the definition 0! = 1.
8.3.2Computing 5! step by step
| Iteration | num (in the condition) | num > 1 | factorial | num (after the update) |
|---|---|---|---|---|
| 1 | 5 | true | 5 | 4 |
| 2 | 4 | true | 20 | 3 |
| 3 | 3 | true | 60 | 2 |
| 4 | 2 | true | 120 | 1 |
| — | 1 | false | 120 | — |
Table 8.4 shows each iteration in one row. The product accumulator factorial starts at 1. In iteration 1, 5 > 1 is true; factorial = 1 × 5 = 5 and num-- lowers num to 4. In iteration 2, 5 × 4 = 20, in iteration 3, 20 × 3 = 60, and in iteration 4, 60 × 2 = 120 is computed. At the end of iteration 4, num becomes 1. The condition 1 > 1 is false and the loop ends. The program prints 120.
The body ran 4 times. The condition num > 1 was chosen because multiplying by 1 does not change the result; num >= 1 would have given the same result and would only have run one extra iteration. Here the counter advances downward. Because the update is num--, num decreases by 1 in every iteration and finally drops to 1. It is this progress that makes the loop end.
The same computation can also be written with for: for (int i = 2; i <= 5; i++) factorial *= i;. Both forms are correct. Because the number of repetitions is known in advance, for is slightly more readable here. The factorial grows very fast: 12! = 479,001,600 fits in an int, 13! = 6,227,020,800 does not. An int can hold at most 2,147,483,647. If 13! is computed with int, Java gives no error; the value silently wraps around and a wrong number such as 1932053504 is printed. That is why long is used in factorial computations. A long is enough up to 20!; 21! does not fit in a long either.
8.4The do-while loop
8.4.1Syntax and order of execution
In some jobs, the body has to run at least once. Consider a menu program. The user cannot make a choice before the menu is printed on the screen; and until the choice is made, the answer to the question “should we exit?” is not known. For this kind of job Java has the do-while loop.
The do-while loop is a loop written as do { body } while (condition); that asks the condition after every iteration. The body runs once without looking at the condition; the later iterations depend on the condition. Such loops are called post-test loops.
The following program reads a choice from the user. If the choice is 1, it prints “Hello!”. It repeats this until the user enters 0:
Scanner in = new Scanner(System.in);
int choice;
do {
System.out.print("Choice (1/0): ");
choice = in.nextInt();
if (choice == 1)
System.out.println("Hello!");
} while (choice != 0);
System.out.println("Goodbye");The Scanner class is used to read from the keyboard. The line import java.util.Scanner; must be written at the top of the file. The call in.nextInt() waits until the user enters an integer and presses Enter, and returns the number entered.
choice = nextInt()) come before the condition. If the condition is true, the arrow goes back up to the start of the body.When Figure 8.5 is compared with the for and while diagrams, the difference is seen at once: the decision box is not at the start of the loop but at its end. The variable choice has been declared before the loop but has not been given a value. Java does not allow an unassigned local variable to be read. No problem arises here, because the condition is asked for the first time after the body, and by that time the line choice = in.nextInt(); has certainly run.
Two details need care in the syntax. First, there is a semicolon at the end of the line while (choice != 0); in for and while loops there is no semicolon at this place. Second, the variable used in the condition must be declared before the loop. If choice had been declared inside the body, its scope would have been limited to the body and it could not have been used in the while line.
8.4.2Tracing a menu loop
Let the user enter 1, 2, and 0 in turn. Table 8.5 shows the three iterations of the loop.
| Iteration | choice read | choice == 1 | Printed | choice != 0 |
|---|---|---|---|---|
| 1 | 1 | true | Choice (1/0): and Hello! | true |
| 2 | 2 | false | Choice (1/0): | true |
| 3 | 0 | false | Choice (1/0): | false |
In iteration 1 the body is entered without looking at the condition. The menu is printed, the user enters 1, choice == 1 is true, and “Hello!” is printed. At the end of the iteration 1 != 0 is true and execution returns to the start of the body. In iteration 2, 2 is read. The if condition is false and nothing is printed; because 2 != 0 is true, the loop continues. In iteration 3, 0 is read and 0 != 0 is false. The loop ends and “Goodbye” is printed.
The body ran 3 times and the condition was also asked 3 times. In a pre-test loop, the condition is asked one more time than the body runs. In a post-test loop the two counts are equal. When the program was run on JDK 21 with the same inputs, it gave the output below. Because the inputs were redirected from a file, the numbers the user types are not visible on the screen; that is why the prompt lines fall side by side:
Choice (1/0): Hello!
Choice (1/0): Choice (1/0): GoodbyeIf the user enters 0 at the first choice, the output consists of only one prompt line and “Goodbye”. The menu has still been printed once. This is the natural area of use of the do-while loop: menus and input validation. For example, when asking the user for a grade between 1 and 5, the question must be asked at least once. If the value entered is outside the range, the question is repeated: do { grade = sc.nextInt(); } while (grade < 1 || grade > 5);. For the input 7, 0, 3 the loop runs three iterations and exits with grade = 3.
Using do-while where the body must not run at all. If the condition is false on the first try, while and do-while behave differently. In the following two loops the condition is false from the start (n = m = 5, limit 3). The do-while still runs once, prints 5, and makes n 6. The body of the while loop never runs and m stays 5. The output is 5 | 6 5. In every case where the body may run zero times, a pre-test loop is chosen.
int n = 5;
do {
System.out.print(n + " ");
n++;
} while (n < 3);
int m = 5;
while (m < 3) {
System.out.print(m + " ");
m++;
}
System.out.println("| " + n + " " + m);8.4.3Which loop to choose?
The three loops can be converted into one another. Every for loop can be written as a while loop, and every while loop as a for loop. A do-while can also be written as a while loop with a copy of the body placed in front of it. So the choice is not a matter of capability but of readability. The right loop answers the reader's question “when and how many times does this loop run?” by the shortest route.
| Situation | Choice |
|---|---|
| Count from 1 to n, repeat n times | for |
| Process digits until the number is 0 | while |
| Show a menu, ask until valid input arrives | do-while |
| Add up until the user types “0” | while / do-while |
There are two options in the last row, because both solutions look natural. The solution written with while reads the first number before the loop and the next one at the end of the loop. The solution written with do-while puts the reading at the start of the body but needs a separate check in the body so that the 0 is not added to the sum. Whichever looks clearer is chosen.
8.5break and continue
8.5.1Skipping an iteration and leaving a loop
A loop normally ends only when its condition is false, and the whole body runs in every iteration. Two statements change this arrangement.
break ends the nearest enclosing loop at once; execution continues from the first statement after the loop. continue skips only the rest of that iteration. In a for loop the flow goes to the update (i++), and in a while or do-while loop to the condition; the loop continues.
The following loop counts from 1 to 10. It skips the multiples of 3 and stops when it reaches 8:
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue;
if (i == 8) break;
System.out.print(i + " ");
}
System.out.println("| done");print(i) box and goes straight to i++. The break arrow leaves the loop, to “end of loop”.8.5.2Tracing break and continue
| i | i % 3 == 0 | i == 8 | Result | Output |
|---|---|---|---|---|
| 1 | false | false | 1 is printed | 1 |
| 2 | false | false | 2 is printed | 1 2 |
| 3 | true | not asked | continue: printing is skipped | 1 2 |
| 4 | false | false | 4 is printed | 1 2 4 |
| 5 | false | false | 5 is printed | 1 2 4 5 |
| 6 | true | not asked | continue: printing is skipped | 1 2 4 5 |
| 7 | false | false | 7 is printed | 1 2 4 5 7 |
| 8 | false | true | break: the loop ends | 1 2 4 5 7 |
Table 8.7 gives the result of the two checks for each i. For i = 1, 2, 4, 5, 7 both conditions are false and the number is printed. For i = 3 and i = 6, i % 3 == 0 is true. continue runs, print is skipped, and the flow passes straight to i++. In these iterations the second if is never asked. At i = 8 the first condition is false (8 % 3 = 2), the second is true, and break ends the loop. 9 and 10 are never tried. Execution continues from the line after the loop and the output is:
1 2 4 5 7 | doneThe order of the two statements matters too. In the same structure, if the conditions were i % 4 == 0 and i == 10 and the loop ran up to 12, 4 and 8 would be skipped and break would run at 10. The output would be 1 2 3 5 6 7 9 | done. In this loop, for i = 8 the continue check is made first, so break never gets its turn in that iteration.
break and continue can shorten loops but also make the flow harder to trace. In a loop that exits from the middle of the body, looking at the header is not enough to see when the loop ends; the whole body has to be read. That is why these statements are used sparingly. If the same job can be written clearly with a condition or a flag variable, that way is preferred. The condition prime && i <= n / i in the prime test is an example of this.
8.5.3Labeled break
A plain break ends only the nearest enclosing loop. In two nested loops, a break in the inner loop does not stop the outer loop. When it is necessary to leave both loops at once, Java's labeled break statement is used. A name and a colon are written in front of the outer loop; break name; ends the loop that carries that name.
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j == 4) break outer;
System.out.println(i + " " + j);
}
}
System.out.println("done");The program prints the pairs of i and j from 1 to 3 and stops at the first pair whose product is 4. Table 8.8 shows side by side how the same loop behaves with the labeled and the plain break.
| i | j | i * j | with break outer | with plain break |
|---|---|---|---|---|
| 1 | 1 | 1 | “1 1” is printed | “1 1” is printed |
| 1 | 2 | 2 | “1 2” is printed | “1 2” is printed |
| 1 | 3 | 3 | “1 3” is printed | “1 3” is printed |
| 2 | 1 | 2 | “2 1” is printed | “2 1” is printed |
| 2 | 2 | 4 | exits both loops | the inner loop ends |
| 2 | 3 | 6 | not tried | not tried |
| 3 | 1 | 3 | not tried | “3 1” is printed |
| 3 | 2 | 6 | not tried | “3 2” is printed |
| 3 | 3 | 9 | not tried | “3 3” is printed |
For i = 1, the product is not 4 for j = 1, 2, 3 and three lines are printed. For i = 2, j = 1, the product is 2 and “2 1” is printed. At i = 2, j = 2, 2 · 2 = 4. The labeled break outer leaves both loops at once; i = 3 is never tried. The flow jumps to the line after the outer loop and “done” is printed. The output is 4 number lines and “done”:
1 1
1 2
1 3
2 1
doneIf the label is removed and a plain break is written, at i = 2, j = 2 only the inner loop ends. The outer loop moves to 3 with i++ and the inner loop starts again from j = 1. For 3 the products are 3, 6, 9; none of them is 4 and three more lines are printed. With the plain break, 7 number lines come out:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
doneThe labeled break is useful when something is searched for in nested loops and the whole search must end the moment it is found. The same job can also be done with a flag: when the item is found, found = true is set and !found && is added to the condition of the outer loop. The label can be any valid Java name; common choices are descriptive names such as outer or search.
8.6Loop errors and verification
Loop errors are often not caught by the compiler. The program compiles, runs, and either gives a wrong result or never ends. This section treats four typical problems: infinite loops, double counters, a broken loop invariant, and boundary errors.
8.6.1Infinite loops
An infinite loop is a loop that does not end on its own because its condition never becomes false. The program seems “frozen”: it either prints nothing or prints the same lines endlessly.
i < 5, the counter decreases with i-- as 0, −1, −2, … and moves away from the goal. In the while loop below, there is no update at all and i stays 0.Figure 8.9 shows two typical causes. In the first, the update goes in the wrong direction. In the loop for (int i = 0; i < 5; i--), i decreases in every iteration and i < 5 stays true. In the second, the update has not been written at all. If the body of while (i < 5) { … } has no statement that changes i, the condition keeps its value from the first iteration.
The first loop is infinite in theory. In reality, however, int is a bounded type. When i, after dropping to −2,147,483,648, is decreased once more, overflow occurs and the value wraps around to the largest int, 2,147,483,647. This value is not less than 5 and the loop ends. The number of iterations counted with JDK 21 is below:
| Loops | Iterations | Last i processed |
|---|---|---|
| for (int i = 0; i < 5; i--) | 2147483649 | −2147483648 |
i takes every value from 0 down to −2,147,483,648 once. That is 231 + 1 = 2,147,483,649 iterations, about 2.1 billion. A modern computer can finish this many iterations in a few seconds; if there is printing in the body it takes hours. In practice this loop too counts as infinite and is not a correct program.
Sometimes a loop is deliberately written as infinite: while (true). Servers, game loops, and reading with a sentinel value use this form. The body of such a loop must certainly have a break condition. If a program gets stuck in an infinite loop, it is stopped on the command line with the Ctrl+C keys; development environments have a stop button for this.
Forgetting the braces. In the line int i = 0; while (i < 5) System.out.print(i); i++;, the body is only the statement print(i). Indentation, or being written on the same line, does not make i++ part of the body. i stays 0 and 0 is printed endlessly. Using braces in loops even when the body is a single statement prevents this mistake from the start.
8.6.2The double counter trap
The following loop starts x at 0 and increases it by 0.1. The aim is to run 10 iterations: x = 0.0; 0.1; …; 0.9.
int n = 0;
for (double x = 0; x < 1.0; x += 0.1) {
n++;
}
System.out.println(n);The program prints 11, not 10:
11The cause is that the number 0.1 cannot be represented exactly in binary. In the decimal system 1/3 = 0.333… goes on forever. In the same way, in binary 1/10 = 0.0001100110011…2 goes on forever. double cuts this expansion off at 53 bits. A small rounding error arises in every addition and these errors accumulate. Table 8.10 gives the actual value of x in each iteration in the form Java prints it.
| Iteration | x (when the condition is asked) | x < 1.0 | n (after the body) |
|---|---|---|---|
| 1 | 0.0 | true | 1 |
| 2 | 0.1 | true | 2 |
| 3 | 0.2 | true | 3 |
| 4 | 0.30000000000000004 | true | 4 |
| 5 | 0.4 | true | 5 |
| 6 | 0.5 | true | 6 |
| 7 | 0.6 | true | 7 |
| 8 | 0.7 | true | 8 |
| 9 | 0.7999999999999999 | true | 9 |
| 10 | 0.8999999999999999 | true | 10 |
| 11 | 0.9999999999999999 | true | 11 |
| — | 1.0999999999999999 | false | 11 (loop ends) |
The first deviation is seen at iteration 4: x = 0.30000000000000004. At iteration 9, x = 0.7999999999999999. After 10 additions, x is not exactly 1.0 but 0.9999999999999999. Because this value is less than 1.0, the condition comes out true and the loop runs one extra iteration. When x becomes 1.0999999999999999, the loop ends.
If the condition x != 1.0 had been written, the situation would be worse. Because x is never exactly 1.0 in any iteration, the condition stays true forever and the loop never ends. In a trial, after 1000 iterations x is about 99.9999999999986. The lesson is clear: the loop counter should be an integer. If a real number is needed, it is computed from the counter in each iteration: for (int k = 0; k < 10; k++) { double x = k * 0.1; … }. This loop runs exactly 10 iterations.
Not every decimal step is faulty. 0.25 = 1/4 is represented exactly in binary (0.012). The loop for (double d = 0; d != 1.0; d += 0.25) runs exactly 4 iterations and ends. But thinking each time about which numbers can be represented exactly is error-prone. The safe rule is still the int counter.
8.6.3The loop invariant
It is useful to try a loop with a few inputs, but it is impossible to try every input. One way to see that a loop gives the right result for every input is to find a property that stays true unchanged in every iteration.
A loop invariant is a property that is true at the start of every iteration of the loop. It is true when entering the loop; an iteration does not break it; and when the loop ends it is still true and at that moment gives the desired result.
In the sum loop from 1 to n, the invariant is this: at the start of every iteration, sum = 1 + 2 + … + (i − 1). That is, sum is the sum of the numbers processed so far. Table 8.11 checks this property at the start of every iteration for n = 4.
| i at the start of the iteration | sum | 1 + … + (i − 1) | Invariant |
|---|---|---|---|
| 1 | 0 | 0 (empty sum) | true |
| 2 | 1 | 1 = 1 | true |
| 3 | 3 | 1 + 2 = 3 | true |
| 4 | 6 | 1 + 2 + 3 = 6 | true |
| 5 | 10 | 1 + 2 + 3 + 4 = 10 | true |
The correctness of the invariant is shown in three steps:
- Initialization. Before the first iteration, i = 1 and sum = 0. 1 + … + 0 is an empty sum with no terms, and its value is 0. The invariant is true from the start.
- Maintenance. Suppose that at the start of an iteration sum = 1 + … + (i − 1). The body adds i to the sum: sum = 1 + … + (i − 1) + i. The update increases i by 1. Written with the new i, this is again of the form 1 + … + (i − 1). The invariant is true at the start of the next iteration too.
- Termination. The loop ends when i = n + 1. Writing n + 1 in place of i in the invariant gives sum = 1 + 2 + … + n. This is exactly the desired result.
None of the three steps depends on a specific value of n. That is why the argument holds for every n. In the exponentiation loop the invariant is “at the start of every iteration result = basei”, and in the factorial loop it is “factorial is the product of the numbers multiplied so far”. Being able to state the invariant in one sentence when writing a loop means really knowing what the loop does.
8.6.4Boundary errors
The most common loop error is running one iteration too few or too many. Should the counter start at 0 or 1, should the condition be < or <=? A mistake in these small choices causes the loop to skip the first or last element or to process an extra one.
An off-by-one error is an error that appears when a loop runs one iteration fewer or one more than the correct number. It mostly arises from choosing the starting value (0 or 1) or the comparison operator (< or <=) wrongly.
Let the task be counting from 1 to 5. Figure 8.11 and Table 8.12 show which values four headers process.
| Header | i values processed | Iterations |
|---|---|---|
| for (i = 1; i <= 5; i++) | 1 2 3 4 5 | 5 |
| for (i = 1; i < 5; i++) | 1 2 3 4 | 4 |
| for (i = 0; i <= 5; i++) | 0 1 2 3 4 5 | 6 |
| for (i = 1; i <= 5; i--) | 1 0 −1 −2 … −2147483648 | 2147483650 |
The last header is the same overflow as in the section on infinite loops. i starts at 1 and goes down to −2,147,483,648; that makes 2,147,483,650 iterations. Then the value wraps around and the loop ends.
Another frequently seen pattern is counting from 0. Arrays and strings are numbered from 0. That is why the form for (int i = 0; i < 5; i++) is very common in Java programs. This loop runs exactly 5 iterations for i = 0, 1, 2, 3, 4:
int count = 0;
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
count++;
}
System.out.println("| rounds: " + count);0 1 2 3 4 | rounds: 5If the condition i <= 5 is written, i = 5 is processed too and the loop runs 6 iterations. The counter becomes 6 instead of 5:
0 1 2 3 4 5 | rounds: 6The way to prevent boundary errors is a simple check. After a loop is written, three questions are asked: what value does the counter take in the first iteration, what value does it take in the last, and how many iterations does it run in total? In the form for (int i = a; i < b; i++) the number of iterations is b − a, and in the form for (int i = a; i <= b; i++) it is b − a + 1. These two formulas catch most boundary errors without running the code.
8.7The digit pattern
Most problems solved with loops rest on a few common patterns. Once a pattern is understood, the same skeleton is reused in different problems with small changes. All the examples in this section process the digits of an integer one by one. Counting digits, summing digits, reversal, palindromes, Armstrong numbers, and decimal-to-binary conversion are variations of the same loop.
A pattern is a solution skeleton that recurs in many problems. A loop pattern determines the type of the loop, its starting values, its condition, and its update; from problem to problem only the operation in the body changes.
8.7.1% 10 and / 10
Two integer operations lie at the base of the pattern. For a positive integer, num % 10 gives the remainder of dividing the number by 10, that is, the last digit: 725 % 10 = 5. num / 10 is integer division; the fractional part is discarded and the last digit is removed: 725 / 10 = 72. When the two operations are applied one after the other, the number is “consumed” digit by digit from right to left:
725 → (5) → 72 → (2) → 7 → (7) → 0
When the number is 0, no digits are left to process. The skeleton of the pattern rests on this observation:
while (rest > 0) {
int digit = rest % 10; // take the last digit
// ... do something with the digit ...
rest /= 10; // drop the last digit
}The loop runs as many iterations as the number has digits. For a six-digit number, 6 iterations are enough. That is why the digit pattern is fast even for very large numbers: the largest int has ten digits and the loop runs at most 10 iterations.
Two details are repeated in every example. First, the loop consumes not the number itself but a copy of it (rest). When the loop ends, rest is 0 but the original number is preserved; in the palindrome and Armstrong tests the result is compared with it. Second, the sign of negative numbers is dropped first. In Java −725 % 10 = −5; the remainder takes the sign of the dividend. If the sign is not dropped, the condition while (rest > 0) is false from the start and the loop never runs.
8.7.2Counting digits
int num = -507;
long rest = num;
if (rest < 0) rest = -rest;
int digits = 0;
do {
digits++;
rest /= 10;
} while (rest > 0);
System.out.println(digits);| Iteration | rest (at the start of the iteration) | digits | rest / 10 | rest > 0 |
|---|---|---|---|---|
| 1 | 507 | 1 | 50 | true |
| 2 | 50 | 2 | 5 | true |
| 3 | 5 | 3 | 0 | false |
Here the digit itself is not needed; only the number of divisions is counted. That is why there is no % 10 in the body. digits is a counter and increases by 1 in every iteration. The program prints 3.
The loop being a do-while is a deliberate choice. For num = 0, a while loop would never run and would find 0 digits. Yet 0 is a one-digit number. Because do-while runs the body at least once, it finds 1 for 0 as well; no special case needs to be written. The same result can also be obtained with a while loop and a check if (num == 0) return 1; placed before it.
There is a reason for the copy being a long too. The smallest value of int is −2,147,483,648 but its largest value is 2,147,483,647. That is why the positive counterpart of −2,147,483,648 does not fit in an int. Even Math.abs(-2147483648) returns −2,147,483,648 again. When the copy is a long, the sign change is done safely and the correct result (10) comes out for the extreme value. If the copy were an int, the method would find 1 for this input.
8.7.3Sum of digits
In the sum of digits, the last digit is added to an accumulator in every iteration:
int num = 725;
long rest = num;
if (rest < 0) rest = -rest;
int sum = 0;
while (rest > 0) {
sum += (int) (rest % 10);
rest /= 10;
}
System.out.println(sum);% 10 takes 5, 2, 7 in turn; the sum becomes 5, 7, 14.| Iteration | rest | rest % 10 | sum | rest / 10 |
|---|---|---|---|---|
| 1 | 725 | 5 | 5 | 72 |
| 2 | 72 | 2 | 7 | 7 |
| 3 | 7 | 7 | 14 | 0 |
The program prints 14: 7 + 2 + 5 = 14. A while is enough here. For num = 0 the body never runs and sum stays 0; this result is correct. The (int) cast is also necessary. Because rest is a long, rest % 10 is also a long and must be explicitly converted when added to an int variable. The compound assignment += would have done this conversion itself; the explicit form shows the reader what is happening. The same loop gives 14 for −725 and 2 for 1001.
8.7.4Reversal and palindromes
To reverse a number, the digits are taken from right to left and a new number is built from left to right. In each iteration the reversed number so far is multiplied by 10; this shifts the old digits one place to the left and frees the units place. The new digit is added in the freed place.
int num = 1221;
int rest = num, rev = 0;
while (rest > 0) {
int digit = rest % 10;
rev = rev * 10 + digit;
rest /= 10;
}
System.out.println(rev);
System.out.println(rev == num); // palindrome?| Iteration | rest | digit | rev = rev × 10 + digit | rest / 10 |
|---|---|---|---|---|
| 1 | 1221 | 1 | 0 × 10 + 1 = 1 | 122 |
| 2 | 122 | 2 | 1 × 10 + 2 = 12 | 12 |
| 3 | 12 | 2 | 12 × 10 + 2 = 122 | 1 |
| 4 | 1 | 1 | 122 × 10 + 1 = 1221 | 0 |
| rev == num | true |
A number whose digits stay the same when read backward is called a palindrome. 1221, 7, and 12321 are palindromes; 123 is not.
The program prints 1221 first and then true. The palindrome test checks whether the reversed number is equal to the original. That is why the loop consumes a copy, not the original number. For 123 the table looks like this:
| Iteration | rest | digit | rev = rev × 10 + digit | rest / 10 |
|---|---|---|---|---|
| 1 | 123 | 3 | 0 × 10 + 3 = 3 | 12 |
| 2 | 12 | 2 | 3 × 10 + 2 = 32 | 1 |
| 3 | 1 | 1 | 32 × 10 + 1 = 321 | 0 |
| rev == num | false |
Forgetting trailing zeros. The reverse of 120 comes out as 21 with this method, because there is no int such as 021. 1200 also turns into 21. The palindrome test still gives the right result for these numbers (120 ≠ 21). But if the reverse has to be shown on the screen as “021”, a character string rather than a number must be built.
8.7.5Armstrong numbers
A number equal to the sum of its digits each raised to the power of the number of digits is called an Armstrong number. For a three-digit number the power is 3: 153 = 13 + 53 + 33 = 1 + 125 + 27.
int num = 153;
int rest = num, sum = 0;
while (rest > 0) {
int r = rest % 10;
sum += r * r * r; // 3 digits: cube
rest /= 10;
}
System.out.println(sum == num);| Iteration | rest | r | r × r × r | sum |
|---|---|---|---|---|
| 1 | 153 | 3 | 27 | 27 |
| 2 | 15 | 5 | 125 | 152 |
| 3 | 1 | 1 | 1 | 153 |
The pattern is the same as the sum of digits; only the cube of the digit is added instead of the digit. The sum reaches 153 and the program prints true. This code is correct only for three-digit numbers, because the power is fixed at 3. A general solution first finds the number of digits and then raises each digit to that power. When all numbers from 100 to 999 are tried, four Armstrong numbers come out: 153, 370, 371, and 407.
8.7.6Converting decimal to binary
The most interesting variation of the pattern is changing the base. When 2 is used instead of 10, n % 2 gives the last bit of the number in binary and n / 2 gives the number with that bit removed. The bits are obtained from right to left. The following program builds the binary representation in an int using decimal digits (1 and 0). Each new bit is written one place to the left of the previous one; for this the variable place grows as 1, 10, 100, ….
int n = 13;
int bin = 0, place = 1;
while (n > 0) {
bin += (n % 2) * place;
place *= 10;
n /= 2;
}
System.out.println(bin); // 1101| Iteration | n | n % 2 | digits | bin | n / 2 |
|---|---|---|---|---|---|
| 1 | 13 | 1 | 1 | 1 | 6 |
| 2 | 6 | 0 | 10 | 1 | 3 |
| 3 | 3 | 1 | 100 | 101 | 1 |
| 4 | 1 | 1 | 1000 | 1101 | 0 |
The program prints 1101. Check: 1 · 8 + 1 · 4 + 0 · 2 + 1 · 1 = 13. This method has a limit. Because the binary representation is built with decimal digits, the result grows quickly. The binary representation of 1023 is ten 1s (1111111111) and fits in an int. The binary representation of 1024 is 10000000000, that is, eleven digits, and does not fit in an int. For this input the program silently overflows and prints 1410065408. For large numbers the result is built as a character string, or Java's Integer.toBinaryString method is used.
8.8Product and divisor patterns
8.8.1Exponentiation
An integer power of a base is repeated multiplication of the base by itself: 24 = 2 × 2 × 2 × 2. The number of repetitions (the exponent) is known; that is why the for loop is suitable.
int base = 2, exp = 4;
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
System.out.println(result);| Iteration | i | i < exp | result |
|---|---|---|---|
| 1 | 0 | true | 2 |
| 2 | 1 | true | 4 |
| 3 | 2 | true | 8 |
| 4 | 3 | true | 16 |
| — | 4 | false | 16 (loop ends) |
The loop runs exactly exp times and multiplies by the base once in each iteration. The invariant has the form “at the start of every iteration result = 2i”. At i = 4 the loop ends and result = 24 = 16. The product accumulator starts at 1. If exp = 0, the loop never runs and the result stays 1; this agrees with 20 = 1.
The code does not cover negative exponents; if exp is negative, the loop never runs and 1 is wrongly found. Large results also exceed the int limit. 230 = 1,073,741,824 fits. 231 comes out as −2,147,483,648 in int, and 232 as 0. Overflow produces no error message; the result is silently wrong.
8.8.2Perfect numbers
In the divisor pattern, the loop tries the possible divisors of the number one by one. If i divides n, n % i == 0.
A number equal to the sum of its positive divisors other than itself is called a perfect number. The smallest example is 6 = 1 + 2 + 3.
int n = 28;
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) sum += i;
}
System.out.println(sum == n);The largest divisor of n other than itself is at most n / 2. A number greater than n / 2 and less than n cannot divide n. That is why the loop stops at n / 2 and avoids unnecessary iterations. Table 8.20 shows the 14 iterations for 28.
| i | 28 % i | Divisor? | sum |
|---|---|---|---|
| 1 | 0 | yes | 1 |
| 2 | 0 | yes | 3 |
| 3 | 1 | no | 3 |
| 4 | 0 | yes | 7 |
| 5 | 3 | no | 7 |
| 6 | 4 | no | 7 |
| 7 | 0 | yes | 14 |
| 8 | 4 | no | 14 |
| 9 | 1 | no | 14 |
| 10 | 8 | no | 14 |
| 11 | 6 | no | 14 |
| 12 | 4 | no | 14 |
| 13 | 2 | no | 14 |
| 14 | 0 | yes | 28 |
The divisors are 1, 2, 4, 7, and 14. Because their sum is 1 + 2 + 4 + 7 + 14 = 28, the program prints true. When tried up to 10,000, only four perfect numbers come out: 6, 28, 496, and 8128.
8.8.3The prime test
An integer greater than 1 that has no positive divisor other than 1 and itself is called a prime number. 0 and 1 are not prime; 2 is the only even prime.
int n = 29;
boolean prime = n >= 2;
for (int i = 2; prime && i <= n / i; i++) {
if (n % i == 0) prime = false;
}
System.out.println(prime);There is an idea in every line of the code. The assignment prime = n >= 2 eliminates 0, 1, and negative numbers from the start. The loop searches for a divisor starting from 2. When a divisor is found, prime = false and the prime && in the condition stops the loop. A flag is used here instead of break. The flag keeps the state in a logical variable and makes the exit condition of the loop visible in the header.
The second idea is the limit of the search. If n has a divisor other than 1 and itself, at least one of these divisors is not greater than √n. Because if n = a × b, a and b cannot both be greater than √n; if they were, their product would exceed n. So it is enough to try i up to √n. The i <= n / i in the condition means the same as i × i ≤ n, but i * i can overflow for a very large i; the division does not overflow.
| n | i | n / i | prime && i <= n / i | n % i | prime |
|---|---|---|---|---|---|
| 29 | 2 | 14 | true | 1 | true |
| 29 | 3 | 9 | true | 2 | true |
| 29 | 4 | 7 | true | 1 | true |
| 29 | 5 | 5 | true | 4 | true |
| 29 | 6 | 4 | false | — | true |
| 21 | 2 | 10 | true | 1 | true |
| 21 | 3 | 7 | true | 0 | false |
| 21 | 4 | not evaluated | false | — | false |
For 29, 4 divisors are tried and none of them divides 29. At i = 6, 6 <= 29 / 6, that is, 6 <= 4, is false. √29 ≈ 5.39 has been passed and there is no need to look for a larger divisor. The program prints true.
For 21, at i = 3, 21 % 3 = 0 and prime = false is set. The update raises i to 4. The first part of the condition, prime, is now false. The && operator short-circuits: if the first operand is false, the second is never evaluated. The loop ends without i <= n / i being tried, and the program prints false. Only 2 divisors have been tried.
The gain from the √n limit is large. For 97, only 8 candidates (2…9) are tried. The largest int, 2,147,483,647, is prime; 46,339 trials are enough for this number. A loop searching from 2 to n − 1 would run more than two billion iterations for the same job.
8.8.4Primes from 1 to n
When the prime test is put inside an outer loop, all primes from 2 to n are listed. For each k, the inner loop performs the prime test:
int n = 20;
for (int k = 2; k <= n; k++) {
boolean prime = true;
for (int i = 2; i <= k / i; i++) {
if (k % i == 0) { prime = false; break; }
}
if (prime) System.out.print(k + " ");
}Here the inner loop ends with break. The variable prime is set to true again for each k; this assignment must be inside the outer loop. If it is moved outside the loop, the flag stays false forever after the first composite number and nothing is printed after 2 and 3. Table 8.22 gives the divisors tried for each k.
| k | Values of i tried | Result |
|---|---|---|
| 2 | none (2 > 2 / 2) | prime, printed |
| 3 | none (2 > 3 / 2) | prime, printed |
| 4 | 2 (4 % 2 = 0, break) | not prime |
| 5 | 2 | prime, printed |
| 6 | 2 (6 % 2 = 0, break) | not prime |
| 7 | 2 | prime, printed |
| 8 | 2 (8 % 2 = 0, break) | not prime |
| 9 | 2, 3 (9 % 3 = 0, break) | not prime |
| 10 | 2 (10 % 2 = 0, break) | not prime |
| 11 | 2, 3 | prime, printed |
| 12 | 2 (12 % 2 = 0, break) | not prime |
| 13 | 2, 3 | prime, printed |
| 14 | 2 (14 % 2 = 0, break) | not prime |
| 15 | 2, 3 (15 % 3 = 0, break) | not prime |
| 16 | 2 (16 % 2 = 0, break) | not prime |
| 17 | 2, 3, 4 | prime, printed |
| 18 | 2 (18 % 2 = 0, break) | not prime |
| 19 | 2, 3, 4 | prime, printed |
| 20 | 2 (20 % 2 = 0, break) | not prime |
For 2 and 3 the inner loop never runs, because 2 <= k / 2 is false (2 / 2 = 1 and 3 / 2 = 1). All even numbers are eliminated on the first try, at i = 2. 9 and 15 are eliminated on the second try, at i = 3. For 17 and 19, 2, 3, and 4 are tried; none divides. The program prints:
2 3 5 7 11 13 17 19 There are 8 primes between 2 and 20, and 25 between 2 and 100. When many primes are needed, faster methods such as the sieve of Eratosthenes are used instead of testing each number separately. When this method finds a prime, it marks all its multiples in a single pass.
8.8.5The Fibonacci sequence
The Fibonacci sequence is the sequence that starts with 0 and 1 and in which every following term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, …
To produce the sequence it is enough to keep only the last two terms. a holds the current term and b the one after it. In every iteration a is printed, the next term is computed, and the two variables are “shifted” one step:
int terms = 5;
long a = 0, b = 1;
for (int i = 0; i < terms; i++) {
System.out.print(a + " ");
long next = a + b;
a = b;
b = next;
}| i | a printed | next = a + b | New a | New b |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 1 | 1 | 2 | 1 | 2 |
| 2 | 1 | 3 | 2 | 3 |
| 3 | 2 | 5 | 3 | 5 |
| 4 | 3 | 8 | 5 | 8 |
The output is 0 1 1 2 3. The order of the shift matters: first a = b, then b = next. If the order is reversed (first b = next, then a = b), a gets the new value of b, not its old value. The two variables are always equal and every term comes out twice the previous one: 0 1 2 4 8. The variable next exists for exactly this reason; it holds the new value without losing the old one.
The sequence grows exponentially. That is why the variables were chosen as long. Even long is not infinite. The 93rd term, 7,540,113,804,746,346,429, fits in a long. The 94th term exceeds the largest value of long (9,223,372,036,854,775,807); the program prints it as a negative number.
8.9Loops that work with input
In the loops so far, the number of iterations depended on numbers inside the program. In loops that read input from the user, the user decides when the loop ends. In these loops the number of iterations is not known in advance, and the natural choice is while or do-while.
8.9.1A number guessing game
The computer keeps a secret number between 1 and 100. The user guesses; the program guides by saying “Higher” or “Lower”. When the guess is right, the number of the try is printed.
Random rnd = new Random();
Scanner in = new Scanner(System.in);
int target = rnd.nextInt(100) + 1; // 1..100
int guess = 0, tries = 0;
while (guess != target) {
guess = in.nextInt();
tries++;
if (guess < target) System.out.println("Higher");
if (guess > target) System.out.println("Lower");
}
System.out.println("Got it in " + tries + " tries");The java.util.Random class is used to generate random numbers; two import lines, for Random and Scanner, are needed at the top of the file. rnd.nextInt(100) gives a number from 0 to 99; adding 1 makes the range 1..100. A different target comes out on every run.
The reason for giving guess = 0 before the loop is the condition. Because the target is between 1 and 100, 0 can never be the target. So guess != target is certainly true at the first check and the loop is entered. The same job could also be written with do-while; in that case this artificial starting value would not be needed.
In a run in which the target is 37, let the user enter 50, 25, and 37 in turn. Table 8.24 shows the three iterations of the game. The table was obtained on JDK 21 by giving the random number generator a seed that yields 37.
| Iteration | guess | tries | Message | Possible range |
|---|---|---|---|---|
| 1 | 50 | 1 | Lower | 1...49 |
| 2 | 25 | 2 | Higher | 26...49 |
| 3 | 37 | 3 | none | found |
The first guess is 50. Because 50 > 37, “Lower” is printed; the target is now in the range 1..49. The second guess is 25; “Higher” is printed and the range drops to 26..49. The third guess is 37. Both ifs are false and no message is printed. The condition 37 != 37 comes out false and the loop ends. The program prints “Got it in 3 tries”.
Always guessing the middle of the range roughly halves the range. A range of 100 numbers shrinks to a single number in 7 halvings; that is why with this strategy every target is found in at most 7 tries. This idea is the basis of binary search.
8.9.2Reading with a sentinel value
If the user does not say in advance how many numbers they will enter, how can the end of the data be recognized? The common solution is to use a special value that cannot be data as the “finished” marker.
A sentinel value is a special value that marks the end of a data sequence and does not itself take part in the data. A sentinel value must be a value that real data can never take.
Scanner sc = new Scanner(System.in);
int sum = 0;
while (true) {
int num = sc.nextInt();
if (num == 0) break;
sum += num;
}
System.out.println("Sum: " + sum);The loop is deliberately written as infinite: while (true). The exit is provided by the break in the middle of the body. As soon as a number is read, it is checked whether it is the sentinel; if it is not, it is added to the sum. Table 8.25 shows the iterations for the input 5, 3, 0.
| num read | num == 0 | sum |
|---|---|---|
| 5 | false | 5 |
| 3 | false | 8 |
| 0 | true | 8 (break) |
The program prints “Sum: 8”. The 0 has not been added to the sum. If the user enters 0 as the first number, the loop ends in the first iteration and “Sum: 0” is printed. For the input 7, −2, 4, 0 the sum is 9; negative numbers are valid data in this program, because the sentinel is only 0.
Checking the sentinel after processing, or choosing a value that could be data as the sentinel. If the line sum += num; is written before the if, the sentinel is also added. While the sentinel is 0 this makes no difference, but if the sentinel were −1, the sum would come out 1 short. In a program such as a grade average, however, 0 can be a real grade. If 0 is chosen as the sentinel, the grade of a student who got 0 is interpreted as “the data is finished”. In such cases a sentinel outside the data range, such as −1, is chosen.
A typical extension of reading with a sentinel is computing an average. Besides the sum, a counter is kept, and after the loop the average is computed as sum / count. Two details must not be forgotten: if no numbers were entered (count = 0), no division is done, and a (double) cast is made before the division. For the input 80, 64, 90, 0 the sum is 234 and the average is 78.0; for 6, 9, 0 the average is 7.5. Without the cast, integer division would give 15 / 2 = 7.
8.10Nested loops
8.10.1Rows and columns
The body of a loop can contain another loop. This structure is called a nested loop. The outer one is called the outer loop and the inner one the inner loop. Tables, grids, multiplication tables, and screen patterns have a row-and-column layout; the natural tool for such output is a nested loop.
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
System.out.printf("(%d,%d) ", row, col);
}
System.out.println();
}(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3) The basic rule of a nested loop is this: the inner loop runs from start to finish in every iteration of the outer loop. When row = 0, the inner loop runs four times for col = 0, 1, 2, 3 and prints four cells from (0,0) to (0,3). When col becomes 4, the inner loop ends. Then println() ends the line. The outer loop moves to 1 with row++ and the inner loop starts again from col = 0. Because the variable col is defined in the header of the inner loop, it is created anew in every outer iteration and gets the value 0.
The inner body runs a total of number of rows × number of columns = 3 × 4 = 12 times. The %d placeholders in printf are filled in order with the values given after the comma. println(), however, is in the body of the outer loop but outside the inner loop. This position makes the output move to the next line once at the end of each row.
The limit of the inner loop can depend on the variable of the outer loop. In that case the number of times the inner body runs is a sum rather than a product. For example, if i runs from 1 to 4 and j from i to 4, the inner body runs 4 + 3 + 2 + 1 = 10 times. The growing triangle pattern is an example of this structure.
8.10.2The multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
} 1 2 3
2 4 6
3 6 9%4d right-justifies each number in a field of 4 characters.When the outer loop has i = 1, the inner loop prints 1, 2, 3 for j = 1, 2, 3. At j = 4 the inner condition becomes false and println ends the line. The same job is repeated for i = 2 and i = 3. The format %4d aligns the numbers in columns: three spaces are added in front of one-digit numbers and two in front of two-digit numbers. When the limits are made 10, the classic 10 × 10 multiplication table comes out; because the largest number is 100, a field of 4 characters is still enough.
8.11Patterns
Screen patterns made of stars or numbers are a classic subject of nested-loop exercises. The patterns themselves are not important; what matters is expressing the layout of an output in numbers and turning those numbers into loop limits. This skill is also needed when working with tables, reports, and matrices.
A pattern is output written line by line in which the number of spaces and characters in each line changes regularly with the line number. The outer loop produces the lines, and the inner loops produce the space and character parts of a line.
8.11.1A method for solving pattern problems
A pattern is turned into code in four steps:
- Draw. The expected output is drawn on graph paper for a small n (for example n = 4). Each square is one character; spaces count as squares too.
- Count. The numbers of spaces and characters in each row are written in a table.
- Relate. The numbers are related to the row number. For example, the sequence 3, 2, 1, 0 is n − row, the sequence 1, 2, 3, 4 is row, and the sequence 1, 3, 5, 7 is 2 × row − 1.
- Code. The outer loop runs as many times as there are rows. For each part of a row (spaces, stars) an inner loop is written; the limit of the inner loop is the formula found in step 3. At the end of the row, println is called.
Table 8.26 collects the formulas of four basic patterns. The numbers on the right were obtained by actually producing the patterns for n = 4 with JDK 21 and counting the spaces and stars in each row.
| Pattern | Spaces | Characters |
|---|---|---|
| Growing triangle | 0 | row |
| Shrinking triangle | 0 | n − row + 1 |
| Right-aligned | n − row | row |
| Pyramid | n − row | 2 × row − 1 |
| Row | Growing | Shrinking | Right-aligned | Pyramid |
|---|---|---|---|---|
| 1 | 0 + 1 | 0 + 4 | 3 + 1 | 3 + 1 |
| 2 | 0 + 2 | 0 + 3 | 2 + 2 | 2 + 3 |
| 3 | 0 + 3 | 0 + 2 | 1 + 3 | 1 + 5 |
| 4 | 0 + 4 | 0 + 1 | 0 + 4 | 0 + 7 |
8.11.2The growing triangle and the number triangle
In the growing triangle, row r has r stars and no spaces. A single inner loop is enough; its upper limit is the variable of the outer loop:
int n = 4;
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}*
**
***
****When row = 1, the inner loop runs only for col = 1 and prints one star. At col = 2, 2 <= 1 is false and println moves to the next line. When row = 2, the inner loop runs twice, when row = 3 three times, and when row = 4 four times. At row = 5 the outer condition becomes false. A total of 1 + 2 + 3 + 4 = 10 stars are printed. In general, a growing triangle of n rows has n(n + 1) / 2 stars; for n = 4, 4 · 5 / 2 = 10.
The same skeleton can print numbers instead of characters. In the number triangle, the variable of the inner loop is written into each cell:
int n = 4;
for (int row = 1; row <= n; row++) {
for (int value = 1; value <= row; value++) {
System.out.print(value + " ");
}
System.out.println();
}1
1 2
1 2 3
1 2 3 4 Again the outer loop determines the row and the upper limit of the inner loop determines the number of elements in the row. The difference is only inside the print call: value + " " is written instead of "*". Because a space is left after every number, there is also a space at the end of the rows; it is not visible on the screen. If the variable of the outer loop had been written instead of the variable of the inner loop, the same number would be repeated in every row: 1, 2 2, 3 3 3, 4 4 4 4.
8.11.3Patterns with spaces: the right-aligned triangle and the pyramid
In the right-aligned triangle, each row consists of two parts: first spaces, then stars. While the number of spaces decreases, the number of stars increases. A separate inner loop is written for each part:
int n = 3;
for (int row = 1; row <= n; row++) {
for (int space = 0; space < n - row; space++)
System.out.print(" ");
for (int star = 0; star < row; star++)
System.out.print("*");
System.out.println();
} *
**
***For n = 3, at row = 1 the space loop runs n − row = 2 times and the star loop once. At row = 2, 1 space and 2 stars are printed. At row = 3, the condition of the space loop 0 < 3 − 3 is false from the start; the loop never runs and the row begins directly with 3 stars. Every row is exactly n = 3 characters. This check shows that the space and star formulas are consistent with each other: (n − row) + row = n.
The pyramid is a variation of the same skeleton. The number of spaces is again n − row, and the number of stars is 2 × row − 1. The stars grow by two in each row; the spaces shrink by one and the group of stars stays in the middle. The following program draws first the pyramid and then, for comparison, the shrinking triangle, for n = 4:
public class Pyramid {
public static void main(String[] args) {
int n = 4;
for (int row = 1; row <= n; row++) {
for (int sp = 0; sp < n - row; sp++) System.out.print(" ");
for (int st = 0; st < 2 * row - 1; st++) System.out.print("*");
System.out.println();
}
for (int row = 1; row <= n; row++) {
for (int st = 1; st <= n - row + 1; st++) System.out.print("*");
System.out.println();
}
}
} *
***
*****
*******
****
***
**
*The first four lines of the output are the pyramid. The last four lines are the shrinking triangle that follows in the same program: the number of stars is n − row + 1, that is, 4, 3, 2, 1. The total number of stars in the pyramid is 1 + 3 + 5 + 7 = 16 = 42. The sum of the first n odd numbers is always n2.
8.11.4The hollow square
In some patterns, what is written in a cell depends not only on the row but on both the row and the column. In the hollow square, the cells on the border are stars and the inner cells are spaces. An if-else goes into the body of the inner loop:
int n = 4;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}****
* *
* *
****A cell is a star if it is on one of the four borders: the first row (i == 0), the last row (i == n - 1), the first column (j == 0), or the last column (j == n - 1). The four conditions are joined with ||; one being true is enough. Because of short-circuiting, the conditions after the first true one are not evaluated. Table 8.28 shows which condition decides in each cell.
| i | j = 0 | j = 1 | j = 2 | j = 3 |
|---|---|---|---|---|
| 0 | * (i == 0) | * (i == 0) | * (i == 0) | * (i == 0) |
| 1 | * (j == 0) | spaces | spaces | * (j == n - 1) |
| 2 | * (j == 0) | spaces | spaces | * (j == n - 1) |
| 3 | * (i == n - 1) | * (i == n - 1) | * (i == n - 1) | * (i == n - 1) |
12 of the 16 cells are border cells and 4 are inner cells. Writing the space in the else branch is mandatory. If this line is left out, nothing is written for the inner cells. The star on the right border shifts left and the middle rows appear as **; the square is ruined.
8.11.5Common mistakes in patterns
Putting the println call inside the inner loop. In that case the line ends after every star. For n = 3, instead of the growing triangle, 1 + 2 + 3 = 6 lines come out one under the other, with a single star in each. println must be written after the closing brace of the inner loop, inside the outer loop.
Other typical mistakes in patterns are these. If < and <= are confused, one character too few or too many comes out in every row; if the counter starts at 0, < is used, and if it starts at 1, <=. If the space loop is written after the star loop, the spaces fall at the end of the row, are invisible, and the pattern is left-aligned. If the variable of the outer loop is changed by mistake in the inner loop (for example, if row++ is written in the inner header), rows are skipped or the loop never ends. Every pattern is protected from these mistakes by checking it row by row with a trace table for a small n.
8.12Test design
That a loop works correctly with a single input does not show that it will work correctly with every input. Loop errors usually appear at the boundaries: in cases where it should not run at all, run one iteration, or process the largest value. A good test set contains an example of each of these cases.
A test case is a pair of an input chosen for a program and the output expected for that input. An edge case is a value at the end of the input range or one that requires special behavior: 0, 1, negative numbers, and the largest or smallest value of a type.
A test set is prepared with these steps:
- For each problem an ordinary, “normal” value is chosen.
- 0, 1, negative values, and values close to the upper limit are chosen separately.
- For each input, the expected result is computed by hand, without running the code.
- The program is run. If the result differs from the expected one, the variables are traced iteration by iteration and the iteration in which the first deviation occurs is found.
Four tests are a sufficient start for the digit-count program. Table 8.29 gives these tests and the results obtained with JDK 21.
| Digit-count test | number | expected | JDK 21 result |
|---|---|---|---|
| Normal | 4096 | 4 | 4 |
| Zero | 0 | 1 | 1 |
| Negative | −507 | 3 | 3 |
| Extreme value | −2147483648 | 10 | 10 |
Each test is chosen to catch a specific mistake. The test for 0 gives the result 0 if the loop was written with while, and reveals the mistake. The negative test reveals that the loop never runs if the sign has not been dropped. The extreme-value test gives a wrong result (1) if the copy is kept as an int. The normal test verifies the basic logic of the code. A solution that passes all four tests contains none of these mistakes.
The same thinking applies to every loop. A sum loop is tried with n = 0 (no iterations), n = 1 (a single iteration), and a large n. A prime test is tried with 0, 1, 2, 4, a square number (for example 25), and a large prime. A pattern program is also run with n = 1 and n = 0. Each of the cases in which the loop runs zero times, once, and many times must be covered by at least one test.
8.13Summary
- Every loop consists of four parts: initialization, condition, body, and update. The update brings the condition closer to its end; if it is forgotten, the loop never ends.
- In the
forloop, the three parts are gathered in the header and the order is “initialization → condition → body → update → condition …”. In a for loop running from 1 to n, the body runs n times and the condition n + 1 times. whileasks the condition before the body anddo-whileafter the body. The body of a while may never run; the body of a do-while runs at least once.- If the number of repetitions is known, for is chosen; while the condition holds, while; if at least one iteration is needed, do-while. The three can be converted into one another; the choice is for readability.
breakends the nearest loop, andcontinueskips only the rest of that iteration. A labeled break leaves nested loops at once.- An infinite loop arises from an update in the wrong direction or one that is never made. A double counter accumulates rounding error; the loop counter should be an int.
- A loop invariant is a property that stays true at the start of every iteration; when the loop ends it shows that the result is correct. Against boundary errors, the first iteration, the last iteration, and the number of iterations are checked.
- The digit pattern (
% 10gives the last digit,/ 10removes it) is used for digit counts, sums of digits, reversal, palindromes, Armstrong numbers, and changing the base. - The divisor pattern rests on the check
n % i == 0. For perfect numbers it is enough to search up to n / 2, and for the prime test up to √n. - A sentinel value is a value that cannot be data; it marks the end of the data and is not itself processed.
- In a nested loop, the inner loop runs from start to finish in every iteration of the outer loop. In patterns, the outer loop produces the row and the inner loops produce the spaces and characters in the row; the numbers are tied to the row number.
- Loops are tested with normal, 0, 1, negative, and extreme values; the expected result is computed by hand beforehand.
8.14Key terms
- loop
- loop body
- iteration
- initialization
- condition
- loop variable
- scope
- counter
- accumulator
- increment / decrement
- pre-test loop
- post-test loop
- menu
- input validation
- break statement
- labeled break
- infinite loop
- overflow
- floating-point number
- loop invariant
- off-by-one error
- pattern
- digit
- integer division
- palindrome
- Armstrong number
- exponent / base
- perfect number
- divisor
- prime number
- flag
- short-circuit evaluation
- Fibonacci sequence
- random number
- sentinel value
- nested loop
- inner loop / outer loop
- pattern (output)
- code tracing
- trace table
- test case
- edge case
8.15Try it yourself
What does the loop
for (int i = 2; i <= 20; i *= 3) System.out.print(i + " ");print? How many times do the body and the condition run?Answer
i takes the values 2, 6, 18 in turn and
2 6 18is printed. After 18, i = 18 × 3 = 54 and 54 <= 20 is false. The body runs 3 times and the condition 4 times. The update does not have to be an increase by 1; here the counter advances by multiplication.After the loop
int x = 1; while (x < 100) x *= 2;, what is x? How many iterations does the loop run?Answer
x becomes 2, 4, 8, 16, 32, 64, 128 in turn. Because 64 < 100 is true, one more iteration runs and x = 128; 128 < 100 is false. The loop runs 7 iterations and x = 128. The loop ends at the first value that makes the condition false; this value may have passed the limit.
After
int k = 10; do { k -= 4; } while (k > 0);runs, what is k? How many times does the body run? What would happen if the same loop were written aswhile (k > 0) k -= 4;with the starting value k = −1?Answer
k becomes 6, 2, −2 in turn. The condition is asked at the end of each iteration; it is true for 6 and 2 and false for −2. The body runs 3 times and k = −2. In the while loop starting with k = −1, −1 > 0 is false from the start; the body never runs and k stays −1. With the same starting value, a do-while would run once and k would be −5.
What does the following loop print?
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) continue; if (i > 7) break; System.out.print(i + " "); }Answer
Even numbers are skipped with continue. Of the odd numbers, 1, 3, 5, and 7 are printed. At i = 9, 9 is odd, the first condition is false, 9 > 7 is true, and break ends the loop. The output is
1 3 5 7. Because i = 8 is skipped with continue, break gets its turn at 9, not at 8.With the digit pattern, what are the sum of digits and the reverse of 4096? What do the reverse of 1200 and the palindrome test give? What do the reverse and the palindrome test give for 0?
Answer
4096: the digits from right to left are 6, 9, 0, 4. The sum is 6 + 9 + 0 + 4 = 19 and the reverse is 6904; because 6904 ≠ 4096, it is not a palindrome. 1200: the digits are 0, 0, 2, 1 and the reverse is built as 0 → 0 → 2 → 21; the result is 21 and it is not a palindrome. For 0 the while loop never runs; rev stays 0 and because 0 == 0, the test gives
true. 0, as a one-digit number, really is a palindrome.After the following nested loop, what is count?
for (int i = 1; i <= 4; i++) for (int j = i + 1; j <= 4; j++) count++;(count is 0 at the start)Answer
For i = 1, j = 2, 3, 4 (3 iterations); for i = 2, j = 3, 4 (2 iterations); for i = 3, j = 4 (1 iteration); for i = 4 the inner loop never runs (5 <= 4 is false). The total is 3 + 2 + 1 + 0 = 6. This number is the number of different pairs that can be chosen from 4 elements: 4 · 3 / 2 = 6.
The following pattern is wanted for n = 4. What are the numbers of spaces and stars in row r? What should the limits of the inner loops be?
**** *** ** *Answer
Row 1 has 0 spaces and 4 stars, row 2 has 1 space and 3 stars, row 3 has 2 spaces and 2 stars, and row 4 has 3 spaces and 1 star. The number of spaces is r − 1 and the number of stars is n − r + 1. Every row is (r − 1) + (n − r + 1) = n characters. Code:
for (int space = 0; space < row - 1; space++)for the spaces,for (int star = 0; star < n - row + 1; star++)for the stars.Does the loop
for (double d = 0; d != 1.0; d += 0.25)end? How many iterations does it run? What would happen if the same loop were written withd += 0.1?Answer
0.25 = 1/4 is represented exactly in binary (0.012). d becomes 0, 0.25, 0.5, 0.75, and exactly 1.0 in turn. The loop runs 4 iterations and ends. 0.1, however, cannot be represented exactly in binary; after 10 additions d = 0.9999999999999999 and in no iteration is it exactly equal to 1.0. With the
!=condition this loop never ends. The safe way is an int counter.The prime test (with the condition
prime && i <= n / i) is run for n = 97. How many divisor candidates are tried? At which value of i and why does the loop end?Answer
i = 2, 3, …, 9 are tried; none divides 97. That is 8 candidates. At i = 9, 9 <= 97 / 9 = 10 is true. At i = 10, 10 <= 97 / 10 = 9 is false and the loop ends. Because √97 ≈ 9.85, there is no need to look for a larger divisor. The program prints
true.
8.16Further reading
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 1.3: conditionals and loops in Java, explained with trace tables and short programs such as powers, harmonic numbers, Newton's method, and binary representation; the online version of the section is at introcs.cs.princeton.edu.
- A. B. Downey, C. Mayfield, Think Java (2nd ed., O'Reilly, 2019): while and for loops and nested loops explained plainly for beginners; the book's online version is free.
- Oracle, The Java Tutorials: the pages while and do-while, for, and branching statements; the official examples of labeled break and continue are on these pages.
8.17References
- P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: while and do-while, for, Branching Statements.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.3 Conditionals and Loops.
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
Related pages: Chapter 8 slides · Study questions · Loop Tracer simulator · Glossary · © Sercan Külcü. All rights reserved.