Skip to main content
Logo image

Section 5.1 While loops

Java has two flavors of loop, while and for. Of the two the while loop is simpler, with fewer moving parts so we’ll talk about it first. The for loop, which we’ll discuss in the next section is actually the one you’ll use most of the time as it has some amenities to make it easier to express common looping patterns.
Syntactically, a while statement looks a lot like an if statement, as you can see in the two listings below:
if (condition) {
    statements;
}
Listing 5.1.1. if statement
while (condition) {
    statements;
}
Listing 5.1.2. while loop
Like with an if statement, when the flow of control reaches a while loop, the first thing that happens is the condition, which must be a boolean expression, is evaluated. If it true, then the body of the loop runs. However, when control reaches the end of the body, it loops back around to the top of the loop and evaluates the condition again, and runs the body again if the condition is true, and so on. When the condition is false, the body is skipped, just like in an if statement when its condition is false.
So the difference between an if statement and a while loop is that the body of the if statement runs either zero or one times, whereas the body of the while loop runs zero or many times.
Here’s a flow chart for a while loop. Follow the arrows in this diagram to see when the condition is checked versus when the body is executed.
Figure 5.1.3. Control flow in a while Loop
If you took AP CSP using a block program like Snap!, you may be familiar with the Repeat Until block. Unfortunately Repeat Until is the opposite of a while loops: it loops until the condition is true where a while loop loops until its condition is false.
For example, the Snap! block below that loops until x is 100 would need to be written in Java with a while loop that runs as long as x is not yet 100, which can be written as x < 100.
Figure 5.1.4. Comparing Snap! repeat until loop to Java while loop
The following video introduces while loops.

Subsection 5.1.1 Three steps to writing a loop

The simplest loops are counting loops where the loop’s condition is based on checking a numeric loop variable that counts up each time the body of the loop executes until it reaches some limit. Thus the loop variable is a counter that controls how many times the loop body executes.
There are three steps to writing a counter-controlled while loop. They are labeled in FigureΒ 5.1.5.
  1. Initialize the loop variable (before the while loop)
  2. Test the loop variable (in the loop header)
  3. Update the loop variable (somewhere in the loop body, usually at the end)
Figure 5.1.5. Three Steps of Writing a Loop

Activity 5.1.1.

Here is a while loop that counts from 1 to 5 that demonstrates the 3 steps of writing a loop. Can you change it to count from 2 to 10?

Activity 5.1.3.

Consider the following code segment. Which of the following can be used as a replacement for the missing loop header so that the loop prints out β€œ0 2 4 6 8 10”?
int count = 0;
/* missing loop header */ {
    System.out.print(count + " ");
    count += 2;
}
  • while (count == 10)
  • This would not print out anything because count = 0 at the start of the loop, so it never equals 10.
  • while (count < 10)
  • This would print out 0 2 4 6 8. Try it in the Active Code window above.
  • while (count <= 10)
  • Yes, try it in the Active Code window above.
  • while (count > 10)
  • This would not print out anything because count = 0 at the start of the loop, so it is not greater than 10.

Subsection 5.1.2 Tracing loops

A really important skill to develop is the ability to trace the values of variables and how they change during each iteration of a loop.
You can create a tracing table that keeps track of the variable values each time through the loop as shown below. This is very helpful on the exam. Studies have shown that students who create tables like this do much better on code tracing problems on multiple choice exams.
Figure 5.1.6. A trace table showing the values of all of the variables each time through the loop. Iteration 0 means before the loop.
Watch the following video for a tracing demo. When you are tracing through code, pretend to be the computer running the code line by line, repeating the code in the loop, and keeping track of the variable values and output.

Activity 5.1.4.

Consider the following code segment. What is count’s value after running this code segment? (To trace through the code, keep track of the variable count and its value through each iteration of the loop.)
int count = 1;
while (count <= 10) {
    count *= 2;
}
count = count - 10;
  • Count is changed inside the loop and after the loop.
  • Count is changed inside the loop and after the loop.
  • Don’t forget to subtract 10 from count after the loop.
  • Yes, the loop will keep multiplying count by 2 to get 2, 4, 8, 16 and then it subtracts 10 from 16 after the loop.
Step through the code above with the visualizer.

Activity 5.1.5.

What does the following code print? (To trace through the code, keep track of the variable x and its value, the iteration of the loop, and the output every time through the loop.)
int x = -5;
while (x < 0) {
   x++;
   System.out.print(x + " ");
}
  • 5 4 3 2 1
  • x is initialized (set) to -5 to start.
  • -5 -4 -3 -2 -1
  • x is incremented (x++) before the print statement executes.
  • -4 -3 -2 -1 0
  • x is set to -5 to start but then incremented by 1 so it first prints -4.

Subsection 5.1.3 Infinite loops

One common error with while is to accidentally create an infinite loop. An infinite loop runs forever because condition never becomes false. If we create an infinite loop by accident, our program may seem to get stuck. For an example, look at the following loop. It looks a lot like the loops earlier in this chapter but it is actually an infinite loop. Can you see why?
int i = 0;
while (i < 10) {
    System.out.println(i);
}
The problem in this loopβ€”and a common way to accidentally create an infinite while loopβ€”is that although it includes steps 1 and 2 (initializing the loop variable and testing it) it forgot step 3 and never changes the loop variable. The loop variable, i, starts at 0 and the loop loops as long as i < 10 which will always be true because there’s no code in the loop that changes i. The simple fix is to add a line that increments i:
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++; // This fixes it!
}
Sometimes we will write an infinite loop on purpose. For example, here’s a simple loop that might exist in a computer-controlled thermostat. The loop header of while (true) is a clear sign that this was intended to be an infinite loop.
while (true) {
    if (tooHot()) {
        turnOnFurnace();
    } else {
        turnOffFurnace();
    }
}
An error that’s the opposite of creating an infinite loop is writing a loop that never runs. (An infinitely short loop!) This can be a problem either in step one, initializing the loop variable or step two, writing the loop condition. For example, if the loop variable is initialized to 10 and test tests that it is less than 10, the loop body will never run.
int i = 10;
while (i < 10){ // This loop will never run!
    System.out.println(i);
    i++;
}

Subsection 5.1.4 Off-by-one errors

Another common error with loops is an off-by-one error where the loop runs one too many or one too few times. This is usually a problem in step two, writing the test condition caused by using the incorrect relational operator such as <= when it should have been < or vice versa.

Activity 5.1.6.

The while loop should print out the numbers from 1 to 8, but it has two bugs. One causes an infinite loop. And the other an off-by-one error. Can you fix the bugs? Try to fix the infinite loop bug first since otherwise you’ll just get an error abut the code taking too long to run.

Subsection 5.1.5 Input-controlled loops

While we can use a while loop as a counting loop to repeat the body of the loop a certain number of times, we’ll see in the next section that that’s more easily done with a for loop. A while loop is more typically used when we don’t know how many times the loop will need to executeβ€”when the condition will eventually become false but it might be after a few iterations or a lot and the only way to find out is to execute the loop.
On such loop of this kind is an input-controlled loop where code in the body accepts input from the user, and that input indicates whether to stop or to keep looping. For example, in the Magpie chatbot lab code below, the while loop stops when the user types β€œBye”.
Scanner in = new Scanner(System.in);
String statement = in.nextLine();
while (!statement.equals("Bye")) {
    System.out.println(getResponse(statement));
    statement = in.nextLine();
}
Notice how the loop variable in this loop is a String not a number. And the condition, statement.equals("Bye") is how we test whether that String is a particular value, "Bye". (More on this in the ChapterΒ 9Β Objects). A special value, like "Bye, that is the sign to stop the loop is called a sentinel value for the loop.
Also notice how the loop still contains a line at the bottom of the loop to update the loop variable with new input from the user. Without that line the loop would either be an infinite loop, endlessly printing out the first thing the user typed or an infinitely short loop if the typed "Bye" as the very first thing.

Subsection 5.1.6 Coding Challenge: Turtle Squares

Do you remember when we used the turtle objects to draw shapes? To create a square without loops we had to repeat code to go forward and turn 90 degrees to the right 4 times like below. This is a lot of repeated code!

Activity 5.1.7.

Can you change the code below to remove the repeated lines of code and use a while loop to draw 4 sides of the square? Did you notice that the code becomes a lot shorter? You should only need 1 call to forward and 1 call to turn in the loop. Whenever you find yourself repeating code, try to use a loop instead!
(If the code below does not work for you, you can copy the code into this replit link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.)

Project 5.1.8.

Can you change the code below to remove the repeated lines of code and use a while loop to draw 4 sides of the square?

Subsection 5.1.7 Summary

  • (AP 2.7.A.1) Iteration statements (loops) change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true. Iteration is a form of repetition.
  • (AP 2.7.B.1) A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates. Here is the general form of a while loop:
    // The statements in a while loop run zero or more times,
    // determined by how many times the condition is true
    int count = 0; // initialize the loop variable
    while (count < 10)  // test the loop variable
    {
        // repeat this code
        // update the loop variable
        count++;
    }
    
  • Loops often have a loop variable that is used in the boolean condition of the loop. Remember the three steps of writing a loop:
    1. Initialize the loop variable
    2. Test the loop variable
    3. Update the loop variable
  • (AP 2.7.A.2) An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
  • (AP 2.7.A.3) The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
  • (AP 2.7.A.4) Off by one errors occur when the iteration statement loops one time too many or one time too few.
  • Input-controlled loops often use a sentinel value that is input by the user like β€œbye” or -1 as the condition for the loop to stop. Input-controlled loops are not on the AP CSA exam, but are very useful to accept data from the user.

Subsection 5.1.8 AP Practice

Activity 5.1.9.

Consider the following code segment.
int n = 35;
int result = 1;
while (n > 0)
{
    int d = n % 10;
    result *= d;
    n /= 10;
}
System.out.println(result);
What is the output after the code has been executed?
  • Keep track of the variables n, d, and result. Watch the tracing video.
  • Correct! The digits in n = 35 are 3 and 5 and 3*5 = 15.
  • Keep track of the variables n, d, and result. Watch the tracing video.
  • Although the sum of the digits in 35 are 8. This code uses multiplication.
  • Keep track of the variables n, d, and result. Watch the tracing video.

Activity 5.1.10.

Consider the following code segment which is intended to print out the even numbers from 0 to 8 (including 8).
int count = 0;
/* missing loop header */
{
    if (count % 2 == 0)
    {
        System.out.println(count);
    }
    count++;
}
Which of the following could replace the missing loop header to ensure that the code segment will work as intended to print out the even numbers from 0 to 8?
  • while (count > 0)
  • This would cause an infinite loop.
  • while (count >= 8)
  • This would not print out anything since count is 0 before the loop and not greater than 8.
  • while (count < 8)
  • This would print out one too few numbers and would stop before it printed out 8.
  • while (count < 10)
  • Correct! This would stop the loop when count is 10.
  • while (count <= 10)
  • This would print out one too many numbers, 0, 2, 4, 6, 8, 10.
You have attempted of activities on this page.