Pyramid · Pattern
Hourglass
Hourglass
PyramidSymbol pattern, solid style, size 5. Changing the rubric, style or size above re-shapes the loops — the structure stays identical while only the printed value or the cell filter changes.
Hourglass · output
Symbol · Solid · size 5
n = int(input("Enter number of rows: "))
# Top — right edge, rows narrow to one
for i in range(1, n + 1):
print((i - 1) * " ", end='')
for j in range(1, n - i + 1 + 1):
print('*', end='')
print()
# Bottom — right edge, rows widen back out
for i in range(n - 1, 1 - 1, -1):
print((i - 1) * " ", end='')
for j in range(1, n - i + 1 + 1):
print('*', end='')
print()Behind the Scenes Execution
registers · line tracking · call stack · memory regions| Address | Variable | Value |
|---|---|---|
| Stack (4) | ||
| 0x200 | n | 5 |
| 0x204 | i | -1 |
| 0x208 | j | -1 |
| 0x20C | count | 0 |
| String Pool (static) (2) | ||
| 0x400000 | pool["*"] | * |
| 0x400008 | pool["\n"] | \n |
| Heap (9) | ||
| 0x3000 | grid[0] | |
| 0x3020 | grid[1] | |
| 0x3040 | grid[2] | |
| 0x3060 | grid[3] | |
| 0x3080 | grid[4] | |
| 0x30A0 | grid[5] | |
| 0x30C0 | grid[6] | |
| 0x30E0 | grid[7] | |
| 0x3100 | grid[8] | |
Hourglass
Two inverted triangles joined at their tips: wide at the very top, squeezed in the middle, wide again at the bottom. The width is n - |i - (n - 1)| — a V-shape that bottoms out at 1.
The size-5 grid
Nine rows of widths 5, 4, 3, 2, 1, 2, 3, 4, 5: the top half spans columns r to 4, the bottom half repeats that pattern in reverse, and a separate final row re-prints the full 5 columns as the base.
Off-by-one traps
That closing row is easy to forget, and without it the hourglass ends at width 4 with only eight rows; the middle row of width 1 must also be printed exactly once.
Step by step
- Type n when the program asks.
- Section top: loop i = 1 to n.
- Print i - 1 spaces, then n - i + 1 symbols — rows narrow to a single cell in the middle.
- Newline after the row.
- Section bottom: loop i = n - 1 down to 1 — the same rows, reversed, widening again.
Complexity
When to use it
- V-shaped row widths
- Playing with the abs() along the diagonal
grid[r] rows in the Heap region and the i / j / count registers on the Stack — every printed character is one write to the grid.Recommended resourcesAffiliate links · may earn us a commission