Java Reference
In-Depth Information
Let's examine one more variation. In the code above, the inner for loop always
does exactly the same thing: It prints exactly 10 stars on a line of output. But what
happens if we change the test for the inner for loop to make use of the outer for
loop's control variable ( i )?
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
In the old version the inner loop always executes 10 times, producing 10 stars on
each line of output. With the new test ( j <= i ), the inner loop will execute i times
with each iteration. But i is changing: It takes on the values 1 , 2 , 3 , 4 , 5 , and 6 . On
the first iteration of the outer loop, when i is 1 , the test j <= i is effectively testing
j <= 1 , and it generates a line with one star on it. On the second iteration of the
outer loop, when i is 2 , the test is effectively testing j <= 2 , and it generates a line
with two stars on it. On the third iteration of the outer loop, when i is 3 , the test is
effectively testing j <= 3 , and it generates a line with three stars on it. This continues
through the sixth iteration.
In other words, this code produces a triangle as output:
*
**
***
****
*****
******
2.4 Managing Complexity
You've learned about several new programming constructs in this chapter, and it's
time to put the pieces together to solve some complex tasks. As we pointed out in
Chapter 1, Brian Kernighan, one of the coauthors of The C Programming Language ,
has said that “Controlling complexity is the essence of computer programming.” In
this section we will examine several techniques that computer scientists use to solve
complex problems without being overwhelmed by complexity.
Scope
As programs get longer, it is increasingly likely that different parts of the program
will interfere with each other. Java helps us to manage this potential problem by
enforcing rules of scope.
 
Search WWH ::




Custom Search