Repeating Loops In Java



One of the more annoying punishments for schoolchildren is to make them write something over and over again on paper or, for a capital offense, on the chalkboard. In one of his frequent trips to the board, cartoon problem child Bart Simpson had to write "I will not trade pants with others" dozens of times. This kind of punishment might work on children, but it definitely would fail on a computer. They can repeat a task with ease.

As you might expect, every one of Bart Simpson's chalkboard punishments has been documented on the World Wide Web. Visit the following address to see the list:

<http://www.ncf.carleton.ca/~co378/HomePage.Chalk.html>

Computer programs are ideally suited to do the same thing over and over again because of loops. A loop is a statement or set of statements that will be repeated in a program. Some loops are set to occur a fixed number of times. Others can loop indefinitely. In the Java programs that you write, you will find many circumstances in which a loop is useful. You can use them to wait until a specific thing has taken place, such as a user clicking on a button. You can also use them to cause the computer to wait and do nothing for a brief period, such as in an animation program.

To create and control loops, you use a loop statement. A loop statement causes a computer program to return to the same place more than once. If the term seems unusual to you, think of what a stunt plane does when it loops: It completes a circle and returns to the place it started the loop. There are three loop statements in Java: for, do, and do-while. These loop statements are often interchangeable in a program because each can be made to work like the others. The choice of which loop statement to use in a program often depends on personal preference, but it's beneficial to learn how all three work. You frequently can simplify a loop section of a program by choosing the right statement.

The following topics will be covered during this hour:

·         Using the for loop

·         Using the do loop

·         Using the do-while loop

·         Exiting a loop prematurely

·         Naming a loop

for Loops

The most complex of the loop statements is for. The for loop is often used in cases where you want to repeat a section of a program for a fixed amount of times. It also can be used if the number of times the loop should be repeated is variable. The following is an example of a for loop:

for (int number = 0; number < 1000; number++) {

    if (number % 12 == 0)

        System.out.println("#: " + number);

}

This loop displays every number from 0 to 999 that is evenly divisible by 12. Every for loop has a variable that is used to determine when the loop should begin and end. This variable often is called the counter. The counter in the preceding loop is number.

The example illustrates the three parts of a for statement:

·         The initialization section: In the first part, the number variable is initialized with a value of 0.

·         The conditional section: In the second part, there is a conditional test like one you might use in an if statement. The test is number < 10000.

·         The change section: The third part is a statement that changes the value of the number variable by using the increment operator.

In the initialization section, you can set up the counter variable that you want to use in the for statement. You can create the variable inside the for statement, as the number variable was created in the example, or you can create the variable elsewhere in the program. In either case, the variable should be given a starting value in this section of the for statement. The variable will have this value when the loop starts.

The conditional section contains a test that must remain true for the loop to continue looping. Once the test is false, the loop will end. In this example, the loop will end when the number variable is no longer smaller than 1,000.

The last section of the for statement contains a Java statement that changes the value of the counter variable in some way. This statement is handled each time the loop goes around. The counter variable has to change in some way, or the loop will never end. For instance, in this example, number is incremented by one using the increment operator ++ in the change section. If number were not changed, it would stay at its original value, 0, and the conditional number < 1000 would always be true.

The statements inside the bracket marks({ }) are also executed during each trip through the loop. The bracketed area is usually where the main work of the loop takes place, although some loops do all of their work in the change section.

The preceding example had two statements within the { and } marks:

if (number % 12 == 0)

        System.out.println("#: " + number);

These statements will be executed 1,000 times. The loop starts by setting the number variable equal to 0. It then adds 1 each pass through the loop and stops when number is no longer less than 1000. Every time number is evenly divisible by 12, the number is displayed next to the text #:.

An unusual term that you might hear in connection with loops is iteration. An iteration is a single trip through a loop. The counter variable that is used to control the loop is often called an iterator.

Each section of a for loop is set off from the other sections with a semicolon (;). A for loop can have more than one variable set up during the initialization section and more than one statement in the change section, as in the following:

for (i = 0, j = 0; i * j < 1000; i++, j += 2) {

    System.out.println(i + " * " + j + " = " i * j);

}

These multiple statement sections of the for loop are set off by commas, as in i = 0, j = 0. This loop will display a list of equations where the i variable is multiplied by the j variable. The i variable increases by 1, and the j variable increases by 2 during each trip through the loop. Once i multiplied by j is no longer less than 1,000, the loop will end.

Sections of a for loop can be empty. An example of this would be if the counter variable has already been created with an initial value in another part of the program, as in the following:

for ( ; displayCount < endValue; displayCount++) {

    // loop statements would be here

}

 

Caution: Because many Java statements end with a semicolon, an easy mistake to make is putting a semicolon at the end of a for statement, as in the following:

for (int i = 0; i < 100; i++); {
value = value + i;
}

In this example, the semicolon puts the statements in the brackets, value = value + i;, outside of the loop. As a result, nothing will happen as the for loop is handled. The program will compile without any errors, but you won't get the results you expect when it runs.

 

while Loops

The while loop does not have as many different sections to set up as the for loop. The only thing it needs is a conditional test, which accompanies the while statement. The following is an example of a while loop:

while ( gameLives > 0) {

    // the statements inside the loop go here

}

This loop will continue repeating until the gameLives variable is no longer greater than 0. The while statement tests the condition at the beginning of the loop, before any statements of the loop have been handled.

When a program reaches the while statement for the first time, if the tested condition is false, the statements inside the loop will be ignored. If the while condition is true, the loop goes around once and tests the while condition again. If the tested condition never changes inside the loop, the loop will keep looping indefinitely.

do-while Loops

The do-while loop is similar in function to the while loop, but the conditional test goes in a different place. The following is an example of a do-while loop:

do {

    // the statements inside the loop go here

} while ( gameLives > 0 );

Like the previous while loop, this loop will continue looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop instead of before them.

When the do loop is reached for the first time as a program runs, the statements between the do and the while are handled automatically. Then the while condition is tested to determine whether the loop should be repeated. If the while condition is true, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the do and while statements that changes the condition tested with while, or the loop will continue indefinitely. The statements inside a do-while loop will always be handled at least once.

If you're still confused about the difference between a while loop and a do-while loop, engage in a little role-playing and pretend you're a teenager who wants to borrow your father's car. If you are a teenager with a case of car envy, all the better. There are two strategies that you can take:

1. Borrow the car first and tell Dad later that you did it.

2.
Ask Dad before you borrow the car.

Strategy 1 has an advantage over Strategy 2 because you get to use the car once even if Dad doesn't want to let you use it. The do-while loop is like Strategy 1 because something happens once even if the loop condition is false the first time while is encountered. The while loop is like Strategy 2 because nothing will happen unless the while condition at the beginning is true. It all depends on the situation in your program. Sams.net makes no warranties express nor implied that your father will be happy if you borrow his car without telling him first.

Exiting a Loop

The normal way to exit a loop is for the condition that is tested to become false. This is true of all three types of loops in Java: for, while, and do-while. However, there might be times when you want a loop to end immediately even if the condition being tested is still true. You can do this with a break statement, as shown in the following code:

while (index <= 1000) {

    index = index + 5;

    if (index == 400)

        break;

    System.out.println("The index is " + index);

}

This loop will continue looping until the value of the index variable is greater than 1,000. However, a special case causes the loop to end even if the index variable is less than or equal to 1,000: If index equals 400, the loop ends immediately.

Another special-circumstance statement that you can use inside a loop is continue. The continue statement causes the loop to exit its current trip through the loop and start over at the first statement of the loop. Consider the following loop:

while (index <= 1000) {

    index = index + 5;

    if (index == 400)

        continue;

    System.out.println("The index is " + index);

}

In this loop, the statements will be handled normally unless the value of index equals 400. In that case, the continue statement causes the loop to go back to the while statement instead of the System.out.println() statement. Because of the continue statement, the loop will never display the following text:

The index is 400

You can use the break and continue statements with all three kinds of Java loop statements.

Naming a Loop

Like other statements in Java programs, loops can be put inside of each other. The following shows a for loop inside of a while loop:

while ( totalCoconuts < 100) {

    for ( int count = 0; count < 10; count++) {

        totalCoconuts = totalCoconuts + count;

        if (totalCoconuts > 400)

            break;

    }

}

The break statement will cause the for loop to end if the totalCoconuts variable equals 400 or greater. However, there might be a case where you want to break out of both loops for some reason. To make this possible, you have to give the outer loop--the while statement--a name. To name a loop, put the name on the line before the beginning of the loop and follow it with a colon (:).

Once the loop has a name, you can use the name after the break or continue statement to indicate which loop the break or continue statement applies to. Note that although the name of the loop is followed by a colon at the spot where the loop begins, the colon is not used with the name in a break or continue statement. The following example repeats the previous one with the exception of one thing: If the totalCoconuts variable equals 400 or more, both loops are ended.

coconutLoop:

while ( totalCoconuts < 100) {

    for ( int count = 0; count < 10; count++) {

        totalCoconuts = totalCoconuts + count;

        if (totalCoconuts > 400)

            break coconutLoop;

    }

 

}

Post a Comment

Previous Post Next Post