Star patterns set 4

Star pattern set 4
Star pattern set 4

If you are in the coders world you must have a knowledge of printing patterns. In coding interview interviewer may ask you print any number pattern , alphabet pattern or an character patterns. We recommend you to follow our patterns series so you will feel comfortable with printing patterns. In this blog post you will find set 4 of star patterns.

We recommend you to solve other types patterns as well –

 Click on the pattern and you will get redirected to the code.

Pattern 1

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

Code for pattern 1

Pattern 2

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

Code for pattern 2

Pattern 3

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

Code for pattern 3

Pattern 4

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

Code for pattern 4

Pattern 5

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

Code for pattern 5

How the patterns in set 4 work

Set 4 covers shapes that interviewers like the most: the diamond, the hourglass and a pattern with an open middle. Each one is a combination of the pyramid and the inverted pyramid from the earlier sets, so the logic you already know is enough.

Logic for each pattern

  • Hourglass (solid or spaced): print an inverted pyramid for the top half (9 stars down to 1), then a normal pyramid for the bottom half (3 stars up to 9). Do not print the single-star row twice.
  • Diamond (solid or spaced): the opposite. Print a pyramid from 1 star up to 9, then an inverted pyramid from 7 stars down to 1.
  • Open middle pattern: print stars on the left and right edges of each row and spaces in between. The number of spaces in the middle grows in the top half and shrinks in the bottom half.

Diamond code in Java

int n = 5;
// upper half: 1, 3, 5, 7, 9 stars
for (int i = 1; i <= n; i++) {
    for (int s = 1; s <= n - i; s++) System.out.print(' ');
    for (int k = 1; k <= 2 * i - 1; k++) System.out.print('*');
    System.out.println();
}
// lower half: 7, 5, 3, 1 stars
for (int i = n - 1; i >= 1; i--) {
    for (int s = 1; s <= n - i; s++) System.out.print(' ');
    for (int k = 1; k <= 2 * i - 1; k++) System.out.print('*');
    System.out.println();
}

Interview tips

  • Say out loud how you will split the shape. A diamond is a pyramid plus an inverted pyramid without the middle row, and that is a strong answer.
  • The lower half of a diamond starts at n - 1, not n, so the widest row is not repeated.
  • Ask whether the size is fixed at 5 or entered by the user, and write the code with the variable n from the start.
  • These patterns take O(n²) time and O(1) extra space.

After this set, try the number, alphabet and character patterns, which use the same row and column loops.

Leave a Reply