Question

I am trying to make a tree, like the following:

  *
 ***
*****
 ===

I am able to get the tree centered, but I can't seem to get the stump to be centered with the rest of the tree. I am stuck on how to do this, any help would be appreciated! (The stump of the tree will always have three equal signs)

        int height = 4;
        int counter = 1;
        int spaces = 20;
        for (int row = 1; row <= height; row++){

           for (int j = 1; j <= spaces; j++){
              System.out.print(" ");
           }

           for (int j = 1; j <= counter; j++){
              System.out.print("*");     
           }

           System.out.println("");
           counter += 2;
           spaces--;


         } // end of outer loop
         for(int i=0; i<3; i++){
            System.out.print("=");
         }
Was it helpful?

Solution

public class A {

    public static void main(String[] args) {

        int height = Integer.parseInt(args[0]);
        int counter = 1;
        int spaces = height-1;
        for (int row = 1; row <= height; row++){

           for (int j = 1; j <= spaces; j++){
              System.out.print(" ");
           }

           for (int j = 1; j <= counter; j++){
              System.out.print("*");
           }

           System.out.println("");
           counter += 2;
           spaces--;
         } // end of outer loop
         counter-=2; // length of last line
         for(int i=1; i<=counter/2-1; i++){
            System.out.print(" ");
          }
          System.out.print("===");
    }
}

Observe that we leave space equal to (length of last line)/2 in the first row and it keep decreases by 1. We can find length of last line by Arithmetic Progression.

Observe that middle = of === will always be on (length of last line)/2+1 character. And Thus we have to put space till two characters before that that is (length)/2-1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top