Incremental Java
Example of while: Print from 0 to num - 1

Example: Print from 0

Let's change the problem a little. Instead of printing from 1, print from 0. However, we still want to run num iterations.

Let's see how this works. We can print from 1 to 10. That's 10 iterations. If we start at 0, we print from 0 to what number to get 10 iterations? The answer is 9.

In general, if you want num iterations, you print from 0 to num - 1.

Let's modify the code to do this:

// Prints from 1 to num
public int printRange( int num ) 
{
   int count = 0 ;            // LINE 1
   while ( count < num )  // LINE 2
   {
      System.out.println( "Printing " + count ) ; // LINE 3
      count++ ; // LINE 4
   }
}
There are two important changes. One is obvious. One is not-so-obvious. The first change is to initialize count to 0. This makes sense. We want to start printing at 0.

The second change is to the condition. It is now count < num. Before it was count <= num.

The obvious choice for change of condition is: count <= num - 1. After all, we print only to num - 1. However, it turns out that count <= num - 1 is the same as count < num (at least, when the types are int).

It may help to see an example. Would you agree that count <= 9 is the same as count < 10? If count is less than 10, then it must be the case that it is equal to 9 or less. Since count is an int, it can't have a value of 9.5.

It's much more common to see count < num than count <= num - 1. We'll explain why later.