• No results found

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop is:

for(initialization; Boolean_expression; update) {

//Statements }

Here is the flow of control in a for loop:

1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 2. Next, the Boolean expression is evaluated. If it is true, the body of the

loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Let’s go through an example to demonstrate the preceding steps. Consider the following for loop:

for(int j = 1; j <= 1024; j = j * 2) {

System.out.println(j); }

The first step that occurs is j being initialized to 1; j then is tested to see if it is less than or equal to 1024, which is true, so the body of the for loop executes and 1 is displayed. The flow of control then jumps up to the update statement j = j * 2, and j becomes 2. Because 2 is less than or equal to 1024, the loop repeats again and 2 is displayed.

This process repeats, and j becomes 4, 8, 16, and so on until it equals 2048, at which point the loop terminates. The output will look similar to:

1 2 4 8 16 32 64 128 256 512 1024

This could have been done using a while loop similar to the following:

int j = 1; while(j <= 1024) { System.out.println(j); j = j * 2; }

The end result is the same, so I do not want to imply that one technique is better than the other. For loops are widely used, though, and are an important fundamental piece of Java.

As with while loops and do/while loops, it is possible to write a for loop that never executes, which happens when the Boolean expression is initially false. Similarly, you can write an infinite for loop that never terminates, which happens when the Boolean expression never becomes false.

The following ForDemo program contains three for loops. Study the pro- gram and try to determine what the output of the program will be. By the way, I added one statement in the program that does not compile. See if you can guess which line of code it is.

public class ForDemo {

public static void main(String [] args) { //Loop #1 int x = Integer.parseInt(args[0]); long f = 1; for(int i = 1; i <= x; i++) { f = f * i; } System.out.println(“f = “ + f); System.out.println(“i = “ + i); //Loop #2 for(int k = 1; k <= 100; k++) { if(k % 7 == 0) { System.out.println(k); 72 Chapter 3

Comparing the Looping Control Structures

I want to make a general observation about while loops, do/while loops, and for loops. The number of times that a loop repeats does not need to be predetermined. For example, how many times does the do/while loop repeat in the RandomLoop program? Statistically, assuming that the random number generator is truly random, the loop should only have to repeat itself three or four times at the most.

However, it is possible for the loop to have to repeat 10 times or more until a second random number is finally generated that is different from the first random number. So, to answer my own question, the loop will repeat an indeterminate number of times. You have to run the program to see how many times through it takes to generate a second, unique random number.

What if you knew exactly how many times you needed to repeat something? For exam- ple, suppose that I have 20 students in a calculus class and I need to compute the exam score for each student. I will need to repeat a task 20 times. I can use a while loop or a do/while loop, but my preferred choice in this situation would be a for loop.

You can write a for loop that executes an indeterminate number of times, and you can write a while or do/while loop that executes a predetermined number of times. In general, however, when you know ahead of time exactly how many times you need to repeat a task, a for loop is the control structure of choice. Otherwise, if you need to repeat a task in inde- terminate number of times, a while loop or do/while loop is your best bet.

} } //Loop #3 for(int a = 1, b = 100; a < b; a = a + 2, b = b - 4) { System.out.println(“a = “ + a + “ and b = “ + b); } } }

One nice feature of for loops is that you can often tell how many times they will repeat just by looking at the for declaration. For example, the first loop in the ForDemo program repeats x number of times, where x is a value input from the command-line arguments. The second for loop repeats 100 times. It is not clear how many times the third for loop executes, but I will discuss that in detail in a moment.

The first for loop multiplies 1 * 2 * 3 * ... * x, which is the factorial of x. When the variable i is equal to x + 1, the for loop terminates. For example, when x is 7 the output is:

f = 5040

The statement I added that does not compile is:

System.out.println(“i = “ + i);

The variable i was declared in the initialization step, and i goes out of scope once the for loop terminates.

If you want i to have scope outside of the for loop, you need to declare it outside of the for loop.

For example, you could change the beginning of the loop to:

int i;

for(i = 1; i <= x; i++)

Now, the variable i can be used after the for loop, and it will be the value x + 1.

The second for loop in the ForDemo program executes 100 times and prints all of the numbers between 1 and 100 that are divisible by 7. This for loop gen- erates the following output:

7 14 21 28

35 42 49 56 63 70 77 84 91 98

The third for loop demonstrates using the comma operator to perform mul- tiple statements in the update step. The for loop is declared as:

for(int a = 1, b = 100; a < b; a = a + 2, b = b - 4)

Two variables, a and b, are declared and initialized in the initialization step. In the update step, I wanted to add 2 to a and subtract 4 from b. You can have more than one statement in the update step by separating the statements with a comma. This loop executes 17 times, which is how many times it takes for a to become larger than b, and generates the following output:

a = 1 and b = 100 a = 3 and b = 96 a = 5 and b = 92 a = 7 and b = 88 a = 9 and b = 84 a = 11 and b = 80 a = 13 and b = 76 a = 15 and b = 72 a = 17 and b = 68 a = 19 and b = 64 a = 21 and b = 60 a = 23 and b = 56 a = 25 and b = 52 a = 27 and b = 48 a = 29 and b = 44 a = 31 and b = 40 a = 33 and b = 36