for Loops

In the Java programs that you write, you will find many circumstances in which a loop is useful. You can use them to keep doing something several times, such as an antivirus program that opens each new email you receive to look for any viruses. You also can use them to cause the computer to do nothing for a brief period, such as an animated clock that displays the current time once per minute. 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 where it started the loop. 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 number of times. It also can be used if the number of times the loop should be repeated is based on the value of a variable. The following is an example of a for loop:

for (int dex = 0; dex < 1000; dex++) {
 if (dex % 12 == 0) {
 System.out.println("#: " + dex);
 }
}


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 a variable called dex. The example illustrates the three parts of a for statement:

  • The initialization section: In the first part, the dex variable is given an initial 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 dex < 1000.
  • The change section: The third part is a statement that changes the value of the dex variable by using the increment operator.

In the initialization section, you can set up the counter variable you want to use in the for statement. You even can create the variable inside the for statement, as the preceding example does with the integer variable named dex. You also can create the variable elsewhere in the program. In any 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 dex variable is equal to or greater 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, dex is incremented by one using the increment operator ++ in the change section. If dex was not changed, it would stay at its original value, 0, and the conditional dex < 1000 would always be true. The statements inside the bracket marks, { and }, also are 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 their work in the change section. The preceding example had the following statements within the { and } marks:

if (dex % 12 == 0) {
 System.out.println("#: " + dex);
}


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

By the way

An unusual term 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 often is called an iterator.


As you have seen with if statements, a for loop does not require brackets if it contains only a single statement. This is shown in the following example:

for (int p = 0; p < 500; p++)
 System.out.println("I will not speculate on how hot teacher used to be");


This loop will display the text "I will not speculate on how hot teacher used to be" 500 times. Although brackets are not required around a single statement inside a loop, you can use them if desired as a way of making the program easier to understand. The first program you create during this hour will display the first 200 multiples of 9—9 x 1, 9 x 2, 9 x 3, and so on, up to 9 x 200. Because this task is so repetitious, it should be handled with a loop statement such as for. Open your word processor and create a new file. Enter the text of Listing 8.1 and save the file as Nines.java when you're done.

Listing 8.1. The Full Text of Nines.java
1: class Nines {
2: public static void main(String[] arguments) {
3: for (int dex = 1; dex <= 200; dex++) {
4: int multiple = 9 * dex;
5: System.out.print(multiple + " ");
6: }
7: }
8: }


The Nines program contains a for statement in line 3. This statement has three parts:

  • The initialization section: int dex = 1, which creates an integer variable called dex and gives it an initial value of 1.
  • The conditional section: dex <= 200, which must be true during each trip through the loop. When it is not true, the loop ends.
  • The change section: dex++, which increments the dex variable by one during each trip through the loop.

Compile and run the program. If you are using the JDK, you can handle these tasks by using the following commands:

javac Nines.java java Nines


This program produces the following output:

9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171
180 189 198 207 216 225 234 243 252 261 270 279 288 297 306 315
324 333 342 351 360 369 378 387 396 405 414 423 432 441 450 459
468 477 486 495 504 513 522 531 540 549 558 567 576 585 594 603
612 621 630 639 648 657 666 675 684 693 702 711 720 729 738 747
756 765 774 783 792 801 810 819 828 837 846 855 864 873 882 891
900 909 918 927 936 945 954 963 972 981 990 999 1008 1017 1026
1035 1044 1053 1062 1071 1080 1089 1098 1107 1116 1125 1134 1143
1152 1161 1170 1179 1188 1197 1206 1215 1224 1233 1242 1251 1260
1269 1278 1287 1296 1305 1314 1323 1332 1341 1350 1359 1368 1377
1386 1395 1404 1413 1422 1431 1440 1449 1458 1467 1476 1485 1494
1503 1512 1521 1530 1539 1548 1557 1566 1575 1584 1593 1602 1611
1620 1629 1638 1647 1656 1665 1674 1683 1692 1701 1710 1719 1728
1737 1746 1755 1764 1773 1782 1791 1800


The for loop statement is extremely useful. You'll get a lot of practice using it in upcoming hours, because several of the tutorial programs and workshops make use of these loops.

Watch Out!

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;
}


Look closely at the closing parenthesis in the first line of this example. It is followed by a semicolon, which will prevent the loop from running correctly. The semicolon puts the statements in the brackets, value = value + i, outside the loop. As a result, nothing will happen as the for loop is handled. The program might compile without any errors, but you won't get the results you expect when it runs.


      
Comments