Print equilateral triangle in java

Below prints Equilateral Triangle.

public class PrintEqulateralTriangle {
    public static void main(String[] args) {
        int numberOfRow = 10;
        int numberOfStars = numberOfRow + (numberOfRow - 1);
        int median = (numberOfStars+1)/2;
        for(int i=1; i<=numberOfRow; i++){
            int start = (i==1 ? median : (median - i + 1));
            int end = (i==1 ? median : (median + i - 1));
            for(int j=1; j<=end;j++){
                if((j>= start) && (j <= end)){
                System.out.print("* ");
                }else{
                System.out.print("  ");
                }
            }
           System.out.println();
        }
    }
}


Output:
--------

                           *
                        * * *
                     * * * * *
                  * * * * * * *
               * * * * * * * * *
            * * * * * * * * * * *
         * * * * * * * * * * * * *
      * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *

Note: This might not show perfect equilateral triangle in browser due to html rendering. But the when you execute code, it will print perfect equilateral triangle in the console.

Comments

Popular posts from this blog

BEA-000362 Server failed. Reason: [Management:141268]Parsing Failure in config.xml

Oracle OIM - Search and Update Organization using java API

Trim Leading and Trailing spaces from InputText on tab out.