Chapter 10

The while and do-while Loops


CONTENTS

A computer handles repetitive operations especially well-it never gets bored, and it can perform a task as well the 10,000th time as it did the first. Consider, for example, a disk file containing 10,000 names and addresses. If you tried to type labels for all those people, you'd be seeing spots before your eyes in no time. On the other hand, a printer (with the aid of a computer) can tirelessly spit out all 10,000 labels-and with nary a complaint to the union.

Every programming language must have some form of looping command to instruct a computer to perform repetitive tasks. Java features three types of looping: for loops, while loops, and do-while loops. In this chapter, you learn about the latter two types of loops. In the next chapter, you'll cover for loops.

NOTE
In computer programs, looping is the process of repeatedly running a block of statements. Starting at the top of the block, the statements are executed until the program reaches the end of the block, at which point the program goes back to the top and starts over. The statements in the block may be repeated any number of times, from none to forever. If a loop continues on forever, it is called an infinite loop.

The while Loop

One type of loop you can use in your programs is the while loop, which continues running until its control expression becomes false. The control expression is a logical expression, much like the logical expressions you used with if statements. In other words, any expression that evaluates to true or false can be used as a control expression for a while loop. Here's an example of simple while loop:


num = 1;

while (num < 10)

    ++num;

Here the loop's control variable num is first set to 1. Then, at the start of the while loop, the program compares the value in num with 10. If num is less than 10, the expression evaluates to true, and the program executes the body of the loop, which in this case is a single statement that increments num. The program then goes back and checks the value of num again. As long as num is less than 10, the loop continues. But once num equals 10, the control expression evaluates to false and the loop ends.

NOTE
Notice how, in the previous example of a while loop, the program first sets the value of the control variable (num) to 1. Initializing your control variable before entering the while loop is extremely important. If you don't initialize the variable, you don't know what it might contain, and therefore the outcome of the loop is unpredictable. In the above example, if num happened to be greater than 10, the loop wouldn't happen at all. Instead, the loop's control expression would immediately evaluate to false, and the program would branch to the statement after the curly braces. Mistakes like this make programmers growl at their loved ones.

Example: Using a while Loop

Although the previous example has only a single program line in the body of the while loop, you can make a while loop do as much as you want. As usual, to add more program lines, you create a program block using braces. This program block tells Java where the body of the loop begins and ends. For example, suppose you want to create a loop that not only increments the loop control variable, but also displays a message each time through the loop. You might accomplish this task as shown in Listing 10.1.


Listing 10.1  LST10_1.TXT: Using a while Loop.

num = 0;

while (num < 10)

{

    ++num;

    String s = String.valueOf(num);

    g.drawString("num is now equal to:", 20, 40);

    g.drawString(s, 20, 55); 

}


Initialize the loop control variable.
Check whether num is less than 10.
Increment the loop control variable.
Create a string from the value of num.
Display a message on the screen.
Display the value of num.

NOTE
The body of a loop comprises the program lines that are executed when the loop control expression is true. Usually, the body of a loop is enclosed in braces, creating a program block.

The pseudocode given after the listing illustrates how this while loop works. The thing to notice is how all the statements that Java should execute if the loop control expression is true are enclosed by braces. As I mentioned previously, the braces create a program block, telling Java where the body of the loop begins and ends.

CAUTION
Always initialize (set the starting value of) any variable used in a while loop's control expression. Failure to do so may result in your program skipping over the loop entirely. (Initializing a variable means setting it to its starting value. If you need a variable to start at a specific value, you must initialize it yourself.) Also, be sure to increment or decrement the control variable as appropriate in the body of a loop. Failure to do this could result in an infinite loop, which is when the loop conditional never yields a true result, causing the loop to execute endlessly.

Example: Using a while Loop in a Program

As with most things in life, you learn best by doing. So, in this example, you put together an applet that uses a while loop to create its display. Listing 10.2 is the applet's source code, whereas Listing 10.3 is the HTML document that loads and runs the applet. Figure 10.1 shows the Applet8 applet running in Appletviewer. If you need a reminder on how to compile and run an applet, follow these steps:

Figure 10.1 : Applet8 running in Appletviewer.

  1. Type the source code shown in Listing 10.2 and save it in your CLASSES folder, naming the file Applet8.java. (You can copy the source code from the CD-ROM, if you like, and thus save on typing.)
  2. Compile the source code by typing javac Applet8.java at the MS-DOS prompt, which gives you the Applet8.class file.
  3. Type the HTML document shown in Listing 10.3, and save it to your CLASSES folder under the name APPLET8.htmL.
  4. Run the applet by typing, at the MS-DOS prompt, appletviewer applet8.html.

Listing 10.2  Applet8.java: An Applet That Uses a while Loop.

import java.awt.*;

import java.applet.*;



public class Applet8 extends Applet

{

    TextField textField1;

    TextField textField2;



    public void init()

    {

        textField1 = new TextField(5);

        textField2 = new TextField(5);

        add(textField1);

        add(textField2);

        textField1.setText("1");

        textField2.setText("10");

    }



    public void paint(Graphics g)

    {

        g.drawString("Enter start and end values above.", 50, 45);

        String s = textField1.getText();

        int start = Integer.parseInt(s);

        s = textField2.getText();

        int end = Integer.parseInt(s);



        int row = 0;

        int count = start;

        while (count <= end)

        {

            s = "Count = ";

            s += String.valueOf(count++);

            g.drawString(s, 80, row * 15 + 70);

            ++row;

        }

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet8 class from Java's Applet class.
Declare TextField objects called textField1 and textField2.
Override the Applet class's init() method.
Create the two TextField objects.
Add the two TextField objects to the applet.
Initialize the TextField objects to "1" and "10."
Override the Applet class's paint() method.
Print a prompt for the user.
Get the number from the first TextField object.
Convert the number from text to an integer.
Get the number from the second TextField object.
Convert the number from text to an integer.
Initialize the row counter.
Initialize the loop control variable, count.
Loop from the starting value to the ending value.
Initialize a string to "Count = ".
Add the loop counter to the text string.
Draw the text string in the applet's display area.
Increment the row counter.
Override the Applet class's action() method.
Tell Java to redraw the applet's display area.
Tell Java that the action() method finished successfully.

Listing 10.3  APPLET8.htmL: Applet8's HTML Document.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="Applet8.class"

    width=250

    height=350

    name="Applet8">

</applet>


When you run Applet8, type the starting value for the loop in the first box and the ending value for the loop in the second box. (Don't press enter until you've entered both values.) When you do, the program's while loop runs for the values you selected, printing the value of the loop control variable each time through the loop. For example, in Figure 10.1, the while loop has counted from 1 to 10 (the default values for the TextField controls). You can type any numbers you like, however. If you typed 15 in the first box and 30 in the last box, the while loop will count from 15 to 30, as shown in Figure 10.2.

Figure 10.2 : Applet8 will count however you tell it to.

NOTE
If you enter a pair of numbers with a wide range, the applet's output will run off the bottom of the applet. This won't hurt anything, but you'll be unable to see the entire output. In addition, if you make the starting value greater than the ending value, no output will appear in the applet's display area. This is because the while loop's conditional expression never evaluates to true.

The do-while Loop

Java also features do-while loops. A do-while loop is much like a while loop, except a do-while loop evaluates its control expression at the end of the loop rather than at the beginning. So the body of the loop-the statements between the beginning and end of the loop-is always executed at least once. In a while loop, the body of the loop may or may not ever get executed. Listing 10.4 shows how a do-while loop works.


Listing 10.4  LST10_4.TXT: Using a do-while Loop.

num = 0;



do

    ++num;

while (num < 10);


The difference between a do-while loop and a while loop are readily apparent when you look at the listing. As you can see, the loop's conditional expression is at the end instead of the beginning. That is, in the example listing, num will always be incremented at least once. After Java increments num, it gets to the while line and checks whether num is less than 10. If it is, program execution jumps back to the beginning of the loop, where num gets incremented again. Eventually, num becomes equal to 10, causing the conditional expression to be false, and the loop ends.

Example: Using a do-while Loop

Near the beginning of this chapter, you saw an example of a while loop whose body contained multiple statements. By using braces to mark off a program block, you can do the same thing with a do-while loop. Listing 10.5 shows how to create a multiple line do-while loop:


Listing 10.5  LST10_5.TXT: A Multiple-Line do-while loop.

num = 0;



do

{

    ++num;

    String s = String.valueOf(num);

    g.drawString("num is now equal to:", 20, 40);

    g.drawString(s, 20, 55); 

}

while (num < 10);


Initialize the loop control variable.
Begin the do-while loop.
Increment the loop control variable.
Create a string from the value of num.
Display a message on the screen.
Display the value of num.
Determine whether to repeat the loop.

Example: Using a do-while Loop in a Program

Now it's time to put your knowledge of do-while loops to the test. If you haven't yet picked up on the pattern, you may be surprised to learn that the next applet is called Applet9. Applet9 looks and acts a lot like Applet8. In fact, as far as the user is concerned, they are almost exactly the same program. However, the clever among you may have already guessed that Applet9 uses a do-while loop in place of the while loop. This means that regardless of the values the user enters into the applet's TextField controls, the applet will always display at least one line of text. Listing 10.6 is the applet. Modify the HTML document from Listing 10.3, replacing all occurrences of Applet8 with Applet9, in order to run the new version of the applet.


Listing 10.6  Applet9.java: Source Code for Applet9.

import java.awt.*;

import java.applet.*;



public class Applet9 extends Applet

{

    TextField textField1;

    TextField textField2;



    public void init()

    {

        textField1 = new TextField(5);

        textField2 = new TextField(5);

        add(textField1);

        add(textField2);

        textField1.setText("1");

        textField2.setText("10");

    }



    public void paint(Graphics g)

    {

        g.drawString("Enter start and end values above.", 50, 45);

        String s = textField1.getText();

        int start = Integer.parseInt(s);

        s = textField2.getText();

        int end = Integer.parseInt(s);



        int row = 0;

        int count = start;



        do

        {

            s = "Count = ";

            s += String.valueOf(count++);

            g.drawString(s, 80, row * 15 + 70);

            ++row;

        }



        while (count <= end);

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


As long as the user always enters a lower value in the first box and a higher value in the second, the Applet9 applet will perform exactly as Applet8 did. However, the difference appears when the starting value is greater than the ending value. Applet8 produced no text output at all under these conditions, because the while loop evaluates the condition before it executes the body of the loop. As Figure 10.3 shows, Applet9 always displays at least one line of text output, because the loop is evaluated after its body is executed rather than before. In the figure, the user has entered a starting value that's higher than the ending value.

Figure 10.3 : The do-while loop always executes at least once.

Summary

By using loops, you can easily program your applets to perform repetitive operations. Although loops may seem a little strange to you at this point, you'll find more and more uses for them as you write your own applets. Just remember that a while loop may or may not ever execute depending on how the conditional expressions works out. On the other hand, a do-while loop always executes at least once because its conditional is evaluated at the end of the loop rather than at the start. In the next chapter, you'll learn about one last type of loop, called a for loop. As you'll see, you use a for loop when you know exactly how many times a loop must execute.

Review Questions

  1. When do you use loops in a program?
  2. What is the body of a loop?
  3. How does Java determine when to stop looping?
  4. How many times is a while loop guaranteed to execute?
  5. Why is it important to initialize a loop control variable?
  6. What's an infinite loop?
  7. Compare and contrast while and do-while loops?
  8. How many times will the loop shown in Listing 10.7 execute? What will count equal when the loop finishes?

Listing 10.7  LST10_7.TXT: The Loop for Review Question 8.

int count = 10;



do

{

    ++count;

}

while (count <= 15);


Review Exercises

  1. Write a while loop that executes 20 times.
  2. Convert the while loop you wrote in exercise 1 to a do-while loop.
  3. Write a while loop that will result in an infinite loop.
  4. Write a do-while loop that can never execute more than once.
  5. Write a while loop that counts backwards from 20 to 10.
  6. Modify Applet8 so that it totals all the numbers from the user's selected starting value to the ending value. That is, if the user enters 10 and 15 as the starting and ending values, the applet should sum 10, 11, 12, 13, 14, and 15, and then display the result. Name the program WhileApplet.java. Figure 10.4 shows what the final applet should look like. (You can find the solution to this programming problem in the CHAP07 folder of this book's CD-ROM.)
    Figure 10.4 : This is what the WhileApplet applet should look like.