7.2. While Loops

A while loop executes the body of the loop as long as (or while) a Boolean condition is true. When the condition is false execution continues after the body of the while loop.

Note

If the condition is false the first time you check it, the body of the loop will not execute.

../_images/WhileLoopFlow.png

Figure 1: Flow in a while loop

You can use a while loop to repeat the body of the loop a certain number of times as shown above. However, a while loop is typically used when you don’t know how many times the loop will execute. You might use it while processing a string. Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using 1 for l. The following code loops through a string replacing all 1’s with l’s.

The while loop starts on line 9 in the code above. Statements 10 through 13 are the body of the loop (from the opening parenthesis on line 10 to the closing one on line 13).

Note

Java doesn’t require your code to be correctly indented (code moved to the right a few spaces) to make it clear what statements are part of the body of the loop, but it is good practice. On the free response part of the exam, the reader will use the indention when determining the meaning of your code, even if you forget the open or close curly brace.

One thing to be careful about with while loops is making sure that you don’t end up with an infinite loop. An infinite loop is one that never stops (the condition is always true).

// an infinite loop
while (true)
{
   System.out.println("This is a loop that never ends");
}

The infinite loop above is pretty obvious. But, most infinite loops are accidental. They usually occur because you forget to change the thing you are checking in the condition.

7.2.1. Tracing Variables in Loops

A really important skill to develop is the ability to trace the values of variables and how they change during each time through a loop. Click on the Forward button to execute the current line and see how the values of the variables change each time through the loop.

You can create a 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.

../_images/whileLoopTrace.png

Figure 1: A table showing the values of all of the variables each time through the loop. The 0 means before the first loop.

You can also add System.out.println(variable) to print the value of a variable. In the code below I am printing the values of all of the variables before the loop and at the end of the loop body.

Check your understanding

    6-2-1: What does the following code print?

    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.

    6-2-2: What are the values of var1 and var2 when the code finishes executing?

    int var1 = 0;
    int var2 = 2;
    
    while ((var2 != 0) && ((var1 / var2) >= 0))
    {
       var1 = var1 + 1;
       var2 = var2 -1;
    }
    
  • var1 = 1, var2 = 1
  • The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case
  • var1 = 2, var2 = 0
  • The loop stopped because var2 = 0. After the first execution of the loop var1 = 1 and var2 = 1. After the second execution of the loop var1 = 2 and var2 = 0. This stops the loop and doesn't execute the second part of the complex conditional.
  • var1 = 3, var2 = -1
  • The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case
  • var1 = 0, var2 = 2
  • The loop stops one of two ways, when var2 = 0 or when var1 / var2 = 0 - neither is true in this case
  • The loop will cause a run-time error with a division by zero
  • Even though var1 = 2 and var2 = 0 when the conditional is executed the first condition is true so the rest of the complex conditional won't execute.

    6-2-3: What are the values in a after multAll(3) executes?

    private int[ ] a = {1, 3, -5, -2};
    
    public void multAll(int amt)
    {
       int i = 0;
       while (i < a.length)
       {
          a[i] = a[i] * amt;
          i++;
       } // end while
    } // end method
    
  • {1, 3, -5, -2}
  • This would be true if the contents of arrays could not be changed but they can.
  • {3, 9, -15, -6}
  • This code multiplies each value in a by the passed amt which is 3 in this case.
  • {2, 6, -10, -4}
  • This would be correct if we called multAll(2) instead of multAll(3).
  • The code will never stop executing due to an infinite loop
  • The variable i starts at 0 and increments each time through the loop and stops when it equals the number of items in a.

    6-2-4: What are the values in a after mult(2) executes?

    private int[ ] a = {1, 3, -5, -2};
    
    public void mult(int amt)
    {
       int i = 0;
       while (i < a.length)
       {
          a[i] = a[i] * amt;
       } // end while
    } // end method
    
  • {1, 3, -5, -2}
  • Does the value of i ever change inside the loop?
  • {3, 9, -15, -6}
  • Does the value of i ever change inside the loop?
  • {2, 6, -10, -4}
  • Does the value of i ever change inside the loop?
  • The code will never stop executing due to an infinite loop
  • The value of i is initialized to 0 and then never changes inside the body of the loop, so this loop will never stop. It is an infinite loop.

Mixed up programs

        6-2-5: The following method has the correct code to return a string with all a's removed, but the code is mixed up.  Drag the blocks from the left area into the correct order in the right area.  Click on the "Check Me" button to check your solution.public static String remA(String s)
{
---
   int index = 0;
---
   // while still an a in str
   while (s.indexOf("a") >= 0)
   {
      index = s.indexOf("a");
      s = s.substring(0,index) +
          s.substring(index+1);
   }
---
   return s;
---
} // end method
        
Next Section - 7.3. For Loops