0 votes
in Design Patterns by
Write a Java Program to display the pyramid as per the below design.

     *

    * *

   * * *

  * * * *

 * * * * *

1 Answer

0 votes
by
This can be achieved by using nested loops and calculatingly adding spaces and stars as shown in the logic below:

public class InterviewBitPyramid{  

   public static void printPyramid(int n) {  

       for (int i=0; i<n; i++){  // for number of rows

           for (int j=n-i; j>1; j--) {

               System.out.print(" "); //print space

           }  

           //for number of columns

           for (int j=0; j<=i; j++ ) {

               System.out.print("* "); // print star

           }

           //end-line after every row

           System.out.println();

       }

   }

   

   public static void main(String args[]){

       printPyramid(5); //Print Pyramid stars of 5 rows

   }

}

Output:

     *

    * *

   * * *

  * * * *

 * * * * *
...