A Form of Repetition: The “while” Loop#

The reserved word while is used to create a loop when you want to have explicit control and not just when you want to do something for every item in a structure.

Syntax of the while Loop#

The format of the while statement is:

while (<Boolean expression>) {
\(\;\;\;\;\;\) <statements to repeat, i.e. the loop body>
}

As with the for-each loop, the brackets {} are only required if there are multiple statements to repeat, but it is always good practice to include them. When making a while statement, there are three important considerations:

  1. An initialization statement. Usually, you will need a control variable, for example, a counter, to determine how many times the loop will be done. This control variable should be initialized above the loop.

  2. A change statement. The control value should be changed as part of the loop body and this change should move the control variable towards making the Boolean condition false.

  3. The Boolean expression should indicate when the loop will keep executing.



Check Your Control in while Loops

The first time many beginners run their while loops, execution is infinite. Instead, ask yourself a few simple questions before clicking “Run”. Do you have a control variable? Is the control variable initialized? Does the Boolean condition contain the control variable? Is the control variable changing to move towards having a false Boolean condition?



Semantics of the while Loop#

The meaning of the while loop is very specific: check whether the Boolean condition is true, and if so then do the statements in the loop body and jump back to the top of the loop to check again. But if the Boolean condition is false, then the entire loop body is skipped and execution moves to just below the loop body.

Example of the while Loop#

Here is an example of moving through an array of Strings to be able to print the sum of the length of all the Strings. Compared to the for-each version in Examples of for-each Loop, this code is substantially longer since we must introduce control variables.

1.  String[] fruitBasket = {"kiwi", "apple", "orange", "watermelon"};
2.  int sumLen = 0;
3.  int index = 0;

4.  while (index < fruitBasket.length){
5.     sumLen = sumLen + fruitBasket[index].length();
6.     index = index + 1;
7.  }
8.  System.out.println("Sum of all lengths is: " + sumLen);
Sum of all lengths is: 25

Can you identify the three parts of the loop? The initialization statement is index = 0, the change statement is index = index + 1 and the Boolean expression is index < fruitBasket.length. Notice how the change statement is making index bigger each time through the loop and eventually index will no longer be less than the length of the array and the loop will stop.

Here is a visualization of this program running:

1 Lines 1-3 set up memory. An array of four strings is built. Two integers are initialized to zero.


array of fruit, sumLen is 0 index is 0

2 The comparison in line 4 is true as 0 < 4. Thus the body of the loop (lines 5 and 6) will execute. sumLen has four added (the length of “kiwi”) and index increases.

array of fruit, sumLen is 4 index is 1

3 Back to line 4. Again true as 1 < 4. Thus the body of the loop will execute. sumLen has five added (the length of “apple”) and index increases.

array of fruit, sumLen is 9 index is 2

4 Back to line 4. Again true as 2 < 4. Thus the body of the loop will execute. sumLen has six added (the length of “orange”) and index increases.

array of fruit, sumLen is 15 index is 3

5 Back to line 4. Again true as 3 < 4. Thus the body of the loop will execute. sumLen has ten added (the length of “watermelon”) and index increases.

array of fruit, sumLen is 25 index is 4

6 Back to line 4. Now the expression is false, as 4 is not less than 4. The body of the loop does not execute again. We jump to line 8 to print the output.

Here is an example of finding the index of an item in an array of integers. This algorithm is called sequential search because we move through the array and look at each item in the sequence. This is very similar to the for-each version in Examples of for-each Loop since we already needed to track the index.

int[] myArray = {7, 9, 13, 5, 23, 42, 39, 87, 68, 50};
int itemToFind = 68;
int index = 0;     //Starting location in the array
int location = -1; //Use -1 to flag not found

while (index < myArray.length){
   if (myArray[index] == itemToFind){
      location = index;
   }
   index++;
}

if (location == -1){
   System.out.println("Item NOT found");
}
else{
   System.out.println("Item found at location " + location);
}  
Item found at location 8

Practice Questions#

  1. Trace the following program, showing the execution path as a sequence of line numbers and providing a memory diagram and the output:

    1.  int n = 25;
    2.  while (n > 0){
    3.     System.out.print(n + "&");
    4.     n = n / 2;
    5.  }
    6.  System.out.println("DONE");
    
  2. What is n in the program of question 1) above.

  3. What would happen if line 4 of the program in question 1) above was missing?

  4. Write Java code, using a while loop, to sum the odd numbers between 11 and 29, inclusive.

  5. Write Java code, using a while loop, to print the first letter of each item in an array of Strings.

  6. Write Java code, using a while loop, to print the middle letter of each item in an array of Strings. If a String has two middle letters, print them both.

To Solutions