Chapter 11

The for Loop


CONTENTS

In the previous chapter, you got an introduction to looping. Along the way, you learned about while and do-while loops, which are an important part of the Java language. Java also supports another type of loop, called a for loop, that enables you to specify exactly how many times the loop should be executed. In this chapter, you learn to write for loops, as well as how to incorporate them into your Java programs.

Introducing the for Loop

Probably the most often-used loop in programming is the for loop, which instructs a program to perform a block of code a specified number of times. There are many applications for a for loop, including tasks such as reading through a list of data items or initializing an array. (You'll learn about arrays in Chapter 13, "Arrays.") You could, for example, use a for loop to instruct your computer to print 10,000 address labels, reading a new address from a file each time through the loop and sending that address to the printer. Because you don't currently have an address file, however, let's say you want to print a name on the screen 10 times. Listing 11.1 shows one way to do this.


Listing 11.1  LST11_1.TXT: Printing a Name 10 Times.

g.drawString("Alfred Thompson", 50, 50);

g.drawString("Alfred Thompson", 50, 65);

g.drawString("Alfred Thompson", 50, 80);

g.drawString("Alfred Thompson", 50, 95);

g.drawString("Alfred Thompson", 50, 110);

g.drawString("Alfred Thompson", 50, 125);

g.drawString("Alfred Thompson", 50, 140);

g.drawString("Alfred Thompson", 50, 155);

g.drawString("Alfred Thompson", 50, 170);

g.drawString("Alfred Thompson", 50, 185);


If you were to add the lines shown in Listing 11.1 to your Java applet's paint() method, you'd see something like Figure 11.1. As you can see, you've accomplished the task at hand, which is printing a name 10 times. However, you haven't done it in the most efficient way.

Figure 11.1 : This applet prints a name 10 times without using a loop.

Look at Listing 11.1. See all those calls to drawString()? As a computer programmer, whenever you see program code containing many identical instructions, a little bell should go off in your head. When you hear this little bell, you should do one of two things:

  1. Answer your telephone.
  2. Say to yourself, "This looks like a good place for a loop."

Having many lines in your program containing identical instructions makes your program longer than necessary and wastes valuable memory. It also shows poor programming style. Unless you want your programming friends to snicker behind your back, learn to replace redundant program code with program loops.

TIP
To produce programs that are tightly written, shorter, and faster, always try to replace repetitive program code with program loops.

Example: Using a for Loop

Listing 11.1 can be streamlined easily by using a for loop, as shown in Listing 11.2. The output of the second version is identical to the first, but now the listing is shorter and contains no redundant code.


Listing 11.2  LST11_2.TXT: Using a for Loop to Print a Name 10 Times.

int row = 0;



for (int x=0; x<10; ++x)

    g.drawString("Al Thompson", 25, 50 + (x * 15));


Look at the program line beginning with the keyword for. The loop starts with this line. The word for tells Java that you're starting a for loop. There are actually three elements inside the parentheses. The first part, x=1, is called the initialization section. The second part, x<10, is called the condition; the last part, ++x, is called the increment.

All three sections of the for loop, which are separated by semicolons, reference the loop-control variable x. The loop-control variable, which can have any integer-variable name, is where Java stores the current loop count. Notice that the loop-control variable must have been previously declared as an int (integer) variable. You can place this declaration as part of the initialization part of the command.

The initialization section of the for statement is used to initialize the loop-control variable that controls the action. The condition section represents a Boolean condition that should be equal to true for the loop to continue execution. Finally, the increment, which is the third part of the statement, is an expression describing how to increment the control variable. The statement after the for statement is executed each time the loop's conditional expression is found to be true.

Suppose you want to modify Listing 11.2 to print the name 20 times. What would you change? If you answered, "I'd change the 10 in the for line to 20," you win the Programmer of the Week award. If you answered, "I'd change my socks," you better find a different book to read.

Example: Using a for Loop in a Program

The best way to learn about any programming construct is to use it in a program. Listing 11.3 is a short applet called Applet10 that uses a for loop to display a given name 10 times. Listing 11.4 is the HTML document that runs the applet, whereas Figure 11.2 shows the applet running under Appletviewer.

Figure 11.2 : This applet displays, 10 times, whatever name the user types.


Listing 11.3  Applet10.java: Using a for Loop in an Applet.

import java.awt.*;

import java.applet.*;



public class Applet10 extends Applet

{

    TextField textField1;



    public void init()

    {

        textField1 = new TextField(20);

        add(textField1);

        textField1.setText("Moe Howard");

    }



    public void paint(Graphics g)

    {

        g.drawString("Enter a name above.", 70, 45);

        String s = textField1.getText();



        for (int x=0; x<10; ++x)

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

    }



    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 Applet10 class from Java's Applet class.
Declare a TextField object called textField1.
Override the Applet class's init() method.
Create the TextField object.
Add the TextField object to the applet.
Initialize the text in the TextField object to "Moe Howard."
Override the Applet class's paint() method.
Display a prompt for the user.
Get the name from the TextField object.
Loop ten times.
Draw the name in the applet's display area.
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 11.4  APPLET10.htmL: The HTML Document That Runs Applet10.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="Applet10.class"

    width=250

    height=250

    name="Applet10">

</applet>


The Applet10 applet is well explained in the pseudocode following Listing 11.3. However, notice how the loop counter x works in this program. Although the for loop executes 10 times, the largest value stored in x will be 9. This is because the loop counter starts at 0, and counts 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. You might at first expect x to end up being equal to 10, Watch out for this sort of thing in your Java programs, especially if you use the value of the loop counter within the body of the loop or elsewhere in the program. Applet10 uses the loop counter to determine the row at which to print the next name. Keep in mind that, because x is declared as part of the for loop's program block, it can't be accessed outside of that block.

Changing the Increment Value

The previous example of a for loop increments the loop counter by 1. But suppose you want a for loop that counts from 5 to 50 by fives? This could be useful if you need to use the loop counter to display a value, which needs to be incremented by a different number. You can do this by changing the sections of the for loop, like this.


for (x=5; x<=50; x+=5)

This loop doesn't start counting at 1. Rather, the loop variable begins with a value of 5. Then, thanks to the x+=5 statement, the loop variable is incremented by 5 each time through the loop. Therefore, x goes from 5 to 10, from 10 to 15, and so on up to 50, resulting in ten loops.

You can also use a for loop to count backwards, like this:


for (x=50; x>=5; x-=5)

Notice that in the initialization part of the for statement, the higher value is used. Notice also that the increment clause uses a decrement operator, which causes the loop count to be decremented (decreased) rather than incremented.

Example: Looping with Different Increments

If you're a little confused, take a look at Listing 11.5, which shows the Java source code for a small applet called Applet11. This applet's paint() method contains two for loops, one that counts upward by fives and one that counts downward by fives. Each time through the loop, the program prints out the value of the loop control variable, so that you can see exactly what's going on inside the loops. To run this applet, use the HTML document from the previous applet, but replace all occurrences of Applet10 with Applet11. Figure 11.3 shows Appletviewer running the Applet11 applet.

Figure 11.3 : You can use for loops to count forward or backward by any amount that you like.


Listing 11.5  Applet11.java: Using Different Increments with for Loops.

import java.awt.*;

import java.applet.*;



public class Applet11 extends Applet

{

    public void paint(Graphics g)

    {

        int row = 0;



        for (int x=5; x<=40; x+=5)

        {

            String s = "Loop counter = ";

            s += String.valueOf(x);

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

            ++row;

        }



        for (int x=40; x>=5; x-=5)

        {

            String s = "Loop counter = ";

            s += String.valueOf(x);

            

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

            ++row;

        }

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet11 class from Java's Applet class.
Override the Applet class's paint() method.
Initialize the row counter.
Begin the first for loop.
Create the basic display string.
Add the loop counter value to the display string.
Show the string in the applet's display area.
Increment the row counter.
Start the second for loop.
Create the basic display string.
Add the loop counter value to the display string.
Show the string in the applet's display area.
Increment the row counter.

Using Variables in Loops

Just as you can substitute variables for most numerical values in a program, you can also substitute variables for the literals in a for loop. In fact, you'll probably use variables in your loop limits as often as you use literals, if not more. Here's an example of how to use variables to control your for loops:


for (x=start; x<=end; x+=inc)

In this partial for loop, the loop control variable x starts off at the value of the variable start. Each time through the loop, Java increments x by the value stored in the variable inc. Finally, when x is greater than the value stored in end, the loop ends. As you can see, using variables with for loops (or any other kind of loop, for that matter) enables you to write loops that work differently based on the state of the program.

Example: Controlling for Loops with Variables

For this chapter's last applet, you'll apply everything you've learned about for loops. The Applet12 applet, shown in Listing 11.6, enables you to experiment with different starting, ending, and increment values for the for loop contained in the applet's paint() method. Enter the starting value for the loop in the first box, then enter the ending and increment values in the second and third boxes. Don't press Enter until you've filled in all three boxes with the values you want. When you press Enter, the action() method takes over, telling Java to repaint the applet's display area using the new values. Figure 11.5 shows Applet12 running under the Appletviewer application.

Figure 11.4 : Applet12 enables you to experiment with different starting, ending, and increment values.


Listing 11.6  Applet12.java: Advanced for Loops.

import java.awt.*;

import java.applet.*;



public class Applet12 extends Applet

{

    TextField textField1;

    TextField textField2;

    TextField textField3;



    public void init()

    {

        textField1 = new TextField(5);

        textField2 = new TextField(5);

        textField3 = new TextField(5);



        add(textField1);

        add(textField2);

        add(textField3);



        textField1.setText("1");

        textField2.setText("10");

        textField3.setText("1");

    }



    

public void paint(Graphics g)

    {

        g.drawString("Enter loop starting, ending,", 50, 45);

        g.drawString("and increment values above.", 50, 60);



        String s = textField1.getText();

        int start = Integer.parseInt(s);

        s = textField2.getText();

        int end = Integer.parseInt(s);

        s = textField3.getText();

        int inc = Integer.parseInt(s);



        int row = 0;



        for (int x=start; x<=end; x+=inc)

        {

            String s2 = "Loop counter = ";

            s2 += String.valueOf(x);

            g.drawString(s2, 50, row * 15 + 85);

            ++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 Applet12 class from Java's Applet class.
Declare three TextField objects as fields of the class.
Override the Applet class's init() method.
Create the three TextField objects.
Add the three TextField objects to the applet.
Initialize the TextField objects with their starting text.
Override the Applet class's paint() method.
Display a prompt to the user.
Get the entered text and convert it to integers.
Initialize the row counter.
Begin the for loop.
Create the basic display string.
Add the loop counter value to the display string.
Show the 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 method finished successfully.

Summary

The for loop is a versatile programming construct that enables you to create loops that run from a given starting value to a given ending value. The loop's operation also depends on the value of the loop's increment value, which enables you to use the loop control variable to count forward or backward by any given amount. As you'll see, for loops are used a lot in Java programs. (In fact, they're a standard part of virtually all programming languages.) To be sure you understand for loops, look over the following questions and exercises.

Review Questions

  1. How do you know when to use a for loop?
  2. What are the three parts of a for loop?
  3. When does a for loop stop looping?
  4. How can a for loop count backward?
  5. How can a for loop count by tens?
  6. Is it possible to create an infinite loop with a for loop?
  7. How many times will the loop shown below execute? What will x equal when the loop finishes?
    for (int x=3; x<12; x+=2)
    {
    ++count;
    }

Review Exercises

  1. Write a for loop that executes 15 times.
  2. Write a for loop that counts by twos.
  3. Write a for loop that can never execute.
  4. Write a for loop that counts backwards from 20 to 10.
  5. Modify Applet12 so that it contains two loops, one counting forward and the other counting backwards. Name the program ForApplet.java. Figure 11.5 shows what the final applet should look like. (You can find the solution to this programming problem in the CHAP11 folder of this book's CD-ROM.)
    Figure 11.5 : This is what ForApplet should look like.