Are you preparing for the coding round ? if yes then you must know how to print the 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 3 of star patterns.
We recommend you to solve other types patterns as well –
Set 3 is mostly about inverted shapes: pyramids that get narrower from top to bottom, and shapes that shrink and then grow again. These are built by reversing the loop direction or by combining two loops.
Logic for each type
Inverted pyramid (solid or spaced): run the outer loop from n down to 1. In each row print n - i spaces, then 2 * i - 1 stars (solid) or i copies of a star followed by a space (spaced). The first row is the widest.
Right-aligned shrink-and-grow pattern: use one loop for the shrinking half (5 stars down to 1) and a second loop for the growing half (2 stars up to 5). The spaces in the second loop go down as the stars go up.
Shapes with a gap on one side: print the leading spaces and stars as usual, then add a second inner loop for the stars on the other side of the gap.
Inverted pyramid code in Java
int n = 5;
for (int i = n; 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('*'); // 9, 7, 5, 3, 1 stars
}
System.out.println();
}
Interview tips
To invert a pattern, change the direction of the outer loop (i--) and keep the rest of the logic the same.
When a pattern has two halves, write them as two separate loops. This is easier to read than one loop with many conditions.
Check the last row. Off-by-one errors usually show up there, because the shape should end in a single star.