JavaGently Chapter 3 Solutions


Chapter 3, Question 15
 
 
A number triangle. Write a program which uses for-statements and print/ println statements to produce the following triangle:
 
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5


Adapt the program to print the triangle so that the numbers are centred, as below. Adapt it again to print the triangle upside down.
 

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

Solution
 

 
We tackle the non-centered triangle first. Our keen sense of observation reveals to us that in all of the triangles, each number is repeated exactly that number of times. We quickly formulate the method drawNumber to do this:
 
static void drawNumber(int number) {
    for (int i=0; i < number; i++)
          System.out.print(number+" ");

   System.out.println();
}
Now we need to write another method which calls this method repeatedly. The drawTriangle method iterates from 1 to the height of the triangle, calling drawNumber each time:
 
static void drawTriangle(int height) {
  System.out.println();

   for (int i=1; i<=height; i++)
           drawNumber(i);
          
        System.out.println();
}
If we define HEIGHT to be 5, a simple call in the main method (as given below) is all we need.
 
drawTriangle(HEIGHT);
The centered triangles are a bit trickier. To simplify things, we write a method to draw a certain number of spaces.
 
static void drawSpaces(int number) {
    for (int i=0; i < number; i++)
          System.out.print(" ");
}
Now we need to determine how many spaces each line needs. Again, our keen sense of observation comes into play: for the first line, we need 4 spaces, for the second, 3 and so forth. Clearly, we take the height of the triangle and subtract the number of the line to determine how many spaces to draw. We combine a call to drawSpaces and drawNumber within a for loop to solve our little problem.
 
for (int i=1; i<=height; i++) {
 drawSpaces(height-i);
   drawNumber(i);
}
As for the orientation, simply reversing the bounds of the loop suffices:
 
for (int i=height; i>=1; i--) {
 drawSpaces(height-i);
   drawNumber(i);
}
 



[NumberTriangles.java
Please mail any corrections or suggestions to Graeme