Java Reference
In-Depth Information
You could follow the same process you did before and find new expressions that
produce the appropriate number of spaces and asterisks. However, there is an easier
way. This figure is the same as the previous one, except the lines appear in reverse
order. This is a good place to use a decrementing loop to run the for loop backwards:
Instead of starting at 1 and going up to 5 with a ++ update, you can start at 5 and go
down to 1 using a -- update.
The simple way to produce the upward-pointing triangle, then, is with the follow-
ing code:
1 public class DrawCone {
2 public static void main(String[] args) {
3 for (int line = 5; line >= 1; 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 }
Class Constants
The DrawCone program in the last section draws a cone with five lines. How would
you modify it to produce a cone with three lines? Your first thought might be to sim-
ply change the 5 in the code to a 3 . However, that would cause the program to pro-
duce the following output:
*****
*******
*********
which is obviously wrong. If you work through the geometry of the figure, you will
discover that the problem is with the use of the number 11 in the expression that cal-
culates the number of asterisks to print. The number 11 comes from this formula:
2 * (number of lines) + 1
 
Search WWH ::




Custom Search