next up previous contents
Next: Flow control Up: 3 Iteration Previous: For loops   Contents

While loops

Below is an example of a while loop. Like the for loop, it contains a test expression (i<10) and some code inside the loop to be repeated as long as this expression remains true. The variable i must be declared and initialised before the loop as you see on the first line, int i = 0;. The example below does exactly the same thing as the for loop above.

Example:

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

The following example shows another simple use of the while loop. For each loop iteration, x is doubled and the new value is printed out. This continues until x exceeds 1024. Hence powers of two are printed up to 1024.

// Print powers of 2 up to 1024. 
float x = 1;
while ( x < 1024 )
{
    x = x*2;
    System.out.println(x);
}

Exercise 3.2


(5 marks)



Take the example class IfExample2 (page [*]) which you can download from the course web site: http://www.pp.rhul.ac.uk/~george/PH2150/downloads/IfExample2.java. Modify it so the user is asked to re-enter a number if the input is not valid, i.e. outside the requested range. Include the program listing and sample output in your lab book. Hint: use a while loop around the input.



So, which sort of loop should you use -- for or while? They are both very flexible, so in almost any situation, either could be used to create the desired effect. The choice is therefore mainly a question of style and convenience. As a rough guide, for is well-suited to loops which have a definite number of iterations that you know in advance, as in the example above. Is also most appropriate when you need a variable inside the loop which keeps count of the number of iterations, like i in the above examples. A while loop is best when you don't know how many iterations there will be, but you can write a logical expression which tells you whether to continue for another iteration or not. If in doubt, a good rule is to use which ever type of loop seems simplest.

There is a third loop statement, do, which is very similar to while. Again, the example does the same thing as the two previous examples.

int i = 0;
do 
{
    System.out.println(i);
    i++;
} 
while (i < 10);

The only difference between do and while is that the test expression (i<10) is evaluated at the end of each iteration, instead of at the beginning. Therefore the code inside the curly brackets {} is always executed at least once.

Note: it is possible to create an infinite loop, i.e. one which repeats for ever. A simple example would be:

while (true)
{
    // never ends
}
If you have such a loop in your program, with no other means of escape the program will run for ever. If this happens, you can usually stop the program by pressing Ctrl-C.


next up previous contents
Next: Flow control Up: 3 Iteration Previous: For loops   Contents
RHUL Dept. of Physics