The Idea
A star pattern is a shape — a triangle, a pyramid, a diamond — printed to the console using * characters. They look like a party trick, but they're the cleanest way to internalize nested loops. The outer loop walks down the rows; the inner loop fills each row. Get this right once, and 2D arrays, matrix traversal, and grid problems all start to feel familiar.
The Pattern Anatomy
Every pattern boils down to two questions: how many rows? and for each row, how many characters? The row index i drives everything.
The Inner-Loop Formula
Every shape is just a different rule for how many spaces and stars row i gets. Here are the four you'll see most often:
| Pattern | Inner loop runs | Example (i=3) |
|---|---|---|
| Right Triangle | i stars | *** |
| Pyramid | N - i leading spaces, then 2i - 1 stars | ***** (N=5) |
| Inverted Triangle | N - i + 1 stars | *** (N=5) |
| Diamond | Top half: pyramid up to N; bottom half: inverted pyramid | two triangles glued together |
The trick is to always express the inner bounds in terms of i. Once that clicks, every pattern is a 5-minute problem.
Right Triangle — The Simplest Pattern
Start here. Outer loop walks rows 1..N; inner loop prints i stars on row i. That's the whole algorithm.
Pyramid — Centering with Spaces
A pyramid is a right triangle that's been centered. To center row i, you pad the left with N - i spaces, then print 2i - 1 stars. The spaces are what create the symmetry.
Why Practice with Patterns?
- Nested loops become muscle memory. You stop thinking about
forsyntax and start thinking about what each loop represents. - Row/column thinking transfers directly to 2D arrays. Matrix traversal, dynamic programming tables, grid BFS — all the same
(i, j)mental model. - You build intuition for O(N²) complexity. Seeing a triangle of stars grow quadratically as
Nincreases makes time complexity tangible long before you read the formal definition.
Master the four patterns — right triangle, pyramid, inverted triangle, diamond — and you've earned the right to call yourself comfortable with nested loops.