Java Reference
In-Depth Information
Table 2.8
Analysis of Figure
Line
Spaces
Asterisks
1
0
9
2
1
7
3
2
5
4
3
3
5
4
1
column is easy to get from the line number. It equals (line - 1) . The third column
is a little tougher. Because it goes down by 2 every time and the first column goes up
by 1 every time, you need a multiplier of -2. Then you need an appropriate constant.
The number 11 seems to do the trick, so you can make the third column equal (11 -
2 * line) . You can improve your pseudocode, then, as follows:
for (line going 1 to 5) {
write (line 1) spaces on the output line.
write (11 2 * line) asterisks on the output line.
go to a new output line.
}
This pseudocode is simple to turn into a program:
1 public class DrawV {
2 public static void main(String[] args) {
3 for ( int line = 1; line <= 5; line++) {
4 for ( int i = 1; i <= (line - 1); i++) {
5 System.out.print(" ");
6 }
7 for ( int i = 1; i <= (11 - 2 * line); i++) {
8 System.out.print("*");
9 }
10 System.out.println();
11 }
12 }
13 }
Sometimes we manage complexity by taking advantage of work that we have already
done. For example, how would you produce this figure?
*
***
*****
*******
*********
 
Search WWH ::




Custom Search