Problem solving is the best way achieve a good programming logic, 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 2 of star patterns.
We recommend you to solve other types patterns as well –
Set 2 moves from left-aligned shapes to right-aligned triangles and centered pyramids. The new idea is that each row has two parts: leading spaces first, then the stars. If you print the spaces correctly, the stars line up on their own.
Logic for each pattern
Pattern 1, right-aligned triangle: in row i (starting at 1) print n - i spaces and then i stars.
Pattern 2, right-aligned inverted triangle: the reverse. Row 1 has no spaces and 5 stars, and each next row has one more space and one star less.
Pattern 3, left-pointing half diamond: print the right-aligned triangle from 1 to 5 stars, then continue with the inverted one from 4 stars down to 1.
Pattern 4, pyramid with spaced stars: print n - i spaces, then print a star followed by a space i times. The extra space between stars gives the open look.
Pattern 5, solid pyramid: print n - i spaces and then 2 * i - 1 stars, so the rows have 1, 3, 5, 7 and 9 stars.
Pyramid code in Java
int n = 5;
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) {
System.out.print(' '); // leading spaces
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print('*'); // stars: 1, 3, 5, 7, 9
}
System.out.println();
}
Things to remember
For a centered shape, the number of spaces goes down by one each row while the number of stars goes up (by 1 for a right-aligned triangle, by 2 for a pyramid).
Spaces are part of the output. If your stars are not aligned, check the space loop first.
The time complexity is O(n²) and the extra space is O(1).