Java Reference
In-Depth Information
Be sure to check the syntax fi rst to make sure the code compiles, which it does in this
example. The outer loop has a char loop control variable that goes from 'a' to 'f' ,
totaling six iterations. The inner loop has an int loop control variable that goes from 1 to
3 and prints something, so the output will be 6 * 3 = 18 values. The println call on line
8 occurs after the inner loop, so a line break occurs after every three values are printed.
If you carefully go through the steps of displaying the fi rst couple of rows, you will quickly
deduce the remaining rows. The output of these nested loops is
a1 a2 a3
b1 b2 b3
c1 c2 c3
d1 d2 d3
e1 e2 e3
f1 f2 f3
Let's look at another example. Examine the following code and determine if it compiles
and what the output is:
12. for(int a = 1, b = 10; a < b; a++, b = b - 2) {
13. System.out.println(a + b);
14. }
Again, be sure to look for compiler errors fi rst. This code compiles fi ne. You can
initialize two variables in the initialization step, and you can have multiple update
statements as long as they are separated by commas. If you see a loop like this on the exam,
my advice is to carefully step through each iteration. This example might look confusing,
but it actually only iterates three times:
1. a is 1 and b is 10 : Because 1 < 10 is true, 11 displays and the update statement
executes, incrementing a to 2 and decrementing b to 8 .
2. a is 2 and b is 8 : Because 2 < 8 is true, 10 displays and we go back to the update
statement.
3. a is 3 and b is 6 : Because 3 < 6 is true, 9 displays and the updates execute again.
4. a is 4 and b is 4 : Because 4 < 4 is false, we are finished.
Therefore, the output of this example is
11
10
9
Search WWH ::




Custom Search