Comp 110 while Loop Statements

while loops

Remember that a loop is a statement that allows us to perform a specified amount of code multiple times. One such example of a loop is the while loop. 

While loops give us the ability to: 

  • Traverse arrays (visit every element)
  • Execute a line of code a specified number of times
  • Count numbers from 1 to n

While loops are some of the most general-purpose loops, and is most useful when you don't know how many times you need to repeat the loop. Examples include flipping a coin until you land on heads, or reading data from a file when you don't know how much data you'll have to read.

The following is the while loop syntax:

while(<boolean condition>) {
  <while body>
}

It consists of only two main parts, the boolean condition and the while body. 

There are three keys:

  1. You have to declare a counter variable and initialize it to zero (this variable is often named i).
  2. The loop's test will check that the counter variable is less than the # of times you want to repeat
  3. Don't forget! The last step of the repeat block is incrementing your counter variable (i = i + 1 or i++). If you don't increment, you may create an infinite loop!

The "boolean condition"

The boolean condition is the "trigger" of the while loop. Every time the while body executes, the boolean condition is checked. If the result is true, the body will run. If it is false it will not run.  

Take the following examples. Which loops run? Which loops do not run?

int i = 0;
int n = 100;
while(i < n){ //Loop #1
<while body>
}
while(false){ //Loop #2
<while body>
}
while(true){ //Loop #3
<while body>
}
while(n < i){ //Loop #4
<while body>
}

Loop #1 runs. This is because the expression "i < n" evaluates to true.

Loop #2 will never run. This is because the value false is provided! False does not change its value.

Loop #3 will always run. This because no matter what, the boolean condition is true.

Loop#4 does not run. This is because the expression "n<i" is false.

The "while body" or "loop body"

The loop body is defined simply as what is in the while loop. It is the piece of code that is executed over and over. 

Using while loops to count

Take a look at the following loop. What is the output?

int i = 0;
while(i<50){
    System.out.println(i);
    i++;
}
System.out.println("Done");

The output for this loop prints out a list of numbers from 0 to 49. If we step through the code line by line, this is what it does:

  1. Initializes i to 0
  2. Checks to see if i is less than 50. If true, go to step 3. Else go to step 5
  3. Print out the value of i
  4. Increase i by 1. Go to step 2.
  5. Print Done

While loops can also be used to traverse arrays of an unknown length. Take the following example, which prints the contents of an array. 

public static void printContents(int[] a){
    int index = 0;
    while(index < a.length){
        System.out.println(a[index]);
        index++;
    }
}

The above code looks at every element of the array, and prints it out. It accomplishes this by counting upward with index. 

Reverse traverse an array

You do not always have to set i =0 and i<a.length. What if we wanted to count backwards? How can we try this on our own? (Try it out on your own first!)

Answer:

public static void printContents(int[] a){
    int index = a.length-1;
    while(index => 0){
        System.out.println(a[index]);
        index--;
    }
}

Answer: Instead of starting at 0, start at the length of the array, minus 1. (remember that a[a.length] is illegal, but a[a.length-1] is valid). Now we decrease index by 1 each time, and if the index is equal it -1, we exit out while loop.