Print triangle patterns of stars in C and Java

Write a C and Java program to print triangle patterns of stars.


 

This post covers below patterns formed by right-angled triangle and its mirror –

 

Pattern 1: Right-angled Triangle



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

This is one of the most basic and easiest pattern. We can have n rows. 1st row will contain 1 star, 2nd row will contain 2 stars, and so on.. We can use two nested loops to print this pattern where outer loop represents row number (say i) and inner loop simply prints the star pattern i times.

C

Download   Run Code

Java

Download   Run Code

 

Pattern 2: Mirror of Right-angled Triangle


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

Suppose 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 2 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 (i times).

C

Download   Run Code

Java

Download   Run Code

 

Pattern 3: Hollow Right-angled Triangle



* * 
*   * 
*     * 
* * * * * 

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

C

Download   Run Code

Java

Download   Run Code

 

Pattern 4: Mirror of Hollow Right-angled Triangle


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

Here 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