Print pyramid pattern in C and Java

Write a C and Java program to print pyramid pattern of stars. This post covers below patterns formed by pyramid

 

 

 

Pattern 1: Pyramid


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

We have n rows. Here, 1st row will contain (n-1) spaces followed by 1 star, 2nd row will contain (n-2) spaces followed by 3 stars, 3rd row will contain (n-3) spaces followed by 5 stars, and so on.. We can use nested loops to print this pattern where outer loop represents row number (say i) and inner loop prints the space (n-i times) followed by the star pattern (2*i – 1 times).

C

Download   Run Code

Java

Download   Run Code

 

Pattern 2: Inverted Pyramid


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

Suppose we have n rows. First row will contain 0 space followed by 2*n-1 stars, 2nd row will contain 1 space followed by 2*n-3 stars, 3rd row will contain 2 spaces followed by 2*n-5 stars and so on.. We can use nested loops to print this pattern where outer loop represents row number (say i) and inner loop prints the space (i-1 times) followed by the star pattern (2*n-(2*i-1) times).

C

Download   Run Code

Java

Download   Run Code

 

Pattern 3: Hollow Pyramid


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

The idea remains same as Pattern 1 but here we print ‘*’ only for last row and first & last positions for remaining rows. For all other positions, we print space.

C

Download   Run Code

Java

Download   Run Code

 

Pattern 4: Hollow Inverted Pyramid


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

The idea remains the same as Pattern 2 but we print ‘*’ only for last row and first & last cell in each row. All other positions will be filled by spaces.

C

Download   Run Code

Java

Download   Run Code

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of