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 4Let's see if you follow:
There are three key parts of a loop:
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.