Whenever you prepare for Interview you must be aware with 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 1 of star patterns.
We recommend you to solve other types patterns as well –
Every pattern in this set is built with two loops. The outer loop controls the rows and the inner loop controls how many stars are printed in each row. After the inner loop ends, a line break moves to the next row. Once you can read the rows and columns of a pattern, the code almost writes itself.
Logic for each pattern
Pattern 1, square (5 x 5): the outer loop runs 5 times and the inner loop prints 5 stars every time. The number of stars never changes.
Pattern 2, inverted right triangle: row 1 has 5 stars and each row has one star fewer. Start the inner loop at the row number and run it up to 5, or print n - i + 1 stars in row i.
Pattern 3, right triangle: row i prints i stars, so the inner loop runs from 1 to i.
Pattern 4, half diamond: print a growing triangle from 1 to 5 stars, then a shrinking triangle from 4 back to 1. Use two separate outer loops, one for each half.
Pattern 5, sideways hourglass: the reverse of pattern 4. Print a shrinking triangle first (5 down to 1) and then a growing triangle (2 up to 5).
Tips for interviews
Draw the pattern on paper, number the rows, and write how many stars each row has. The relation between the row number and the star count is the whole answer.
Use System.out.print inside the inner loop and System.out.println() after it. Mixing them up is the most common mistake.
Be careful with < and <=. A wrong boundary gives one star too many or too few.
These patterns run in O(n²) time because each row prints up to n stars, and they use O(1) extra space.
Be ready to change the size. Interviewers often ask you to make the pattern work for any n entered by the user.
After you finish this set, practice the other sets, then try number and character patterns, which use the same two-loop idea with different values printed.