Incremental Java
Example of while: Print from 1 to num

Example: Print from 1 to num

Let's implement the following method:
public void printRange( int num ) ;
which prints 1, 2, ..., all the way up to num.

We want to solve this using a loop. A loop repeats the loop body over and over. We call each execution though the loop body an iteration.

How many iterations do we need? Let's say we want to print int values from 1 to 10.

One reasonable guess is to say we need 10 iterations. On the first iteration, we print 1. On the second iteration, we print 2. On the third, we print 3, and so forth.

But first, we need to figure out how to count out 10 iterations. How to do this? First, declare an int variable, and set it to 1. Each time we go through the loop body, increment it by 1. Check to see if we have reached 10. If we have, we can stop.

Let's make one more change. Instead of printing from 1 to 10, we're going to print from 1 to num. This gives our code more flexibility. The number of iterations depends on the value of num.

Here's our first attempt

// Prints from 1 to num
public int printRange( int num ) 
{
   int count = 1 ;            // LINE 1
   while ( count <= num )  // LINE 2
   {
      System.out.println( "Printing " + count ) ; // LINE 3
      count++ ; // LINE 4
   }
}
If num is 4, it prints:
Printing 1
Printing 2
Printing 3
Printing 4
Let's see if you follow:

Tracing

Tracing is a invaluable skill when it comes to learning how to program. You go line by line trying to understand what happens. Once you get experienced, you see the pattern. The loop pretty much does the same regardless of whether num is 10 or 100.

There are three key parts of a loop:

The tricky parts are usually the start and the end, making sure it starts right, and more importantly, that it ends right.

It's useful to trace code for loops with a few iterations, say, 3 to 5, just to get an idea of what's going on. You don't have time to trace 100 iterations, and it's probably isn't any more enlightening to do so. You run into a problem if you don't trace the code, and just hope your logic and reasoning is correct.