Visualize the Diamond pattern, a pyramid stacked on an inverted pyramid, built with two loops.
About this algorithm
The diamond is a pyramid with an inverted pyramid joined underneath, sharing one widest row in the middle. It is drawn in a square grid of 2n - 1 rows and 2n - 1 columns, and the trick is a single "level" value that climbs to the middle and then falls back.
Come to the diamond after the pyramid and the inverted pyramid. It reuses their space and star rule, and adds one idea: mapping the row number to a distance from the middle so a single loop can draw both halves. That mirror trick is common in pattern questions (and in drawing anything symmetric), and you need it again on the butterfly page. A simpler alternative is two separate loops, one for each half, which this page avoids so the symmetry is clear.
There are 2n - 1 rows, not 2n, because the widest row belongs to both halves and is printed once. Rows 0 to n - 1 are the top half; rows n to 2n - 2 are the bottom.
level = i on the top half and level = (2n - 2) - i on the bottom half. The level rises 0, 1, ..., n - 1 and then drops back to 0, so it says how far the row is from a tip.
spaces = n - 1 - level, and the stars fill columns spaces through spaces + 2 × level. So a row at level L holds 2L + 1 stars, exactly as in the pyramid.
Each column j in range gets a star, the rest get spaces, then a newline. The same three lines of code serve every row.
The page loads n = 5, so 9 rows and 9 columns. Rows 0 to 4 have levels 0 to 4 and give 1, 3, 5, 7 and 9 stars, the last one filling the middle row. Rows 5 to 8 have levels 3, 2, 1, 0 and give 7, 5, 3 and 1. Row 8 has 4 leading spaces and one star in column 4, the bottom tip. Total stars: 25 for the top half plus 16 for the bottom, 41, which is n² + (n - 1)². The other 40 of the 81 cells are blank.
Running the top loop for n rows and the bottom loop for n rows as well. The widest line then appears twice and the diamond gets a flat waist. The bottom half must start one level down, at n - 2.
Time: the square grid has (2n - 1)² cells, about 4n², and each is tested once. Space: level, spaces and the star bound are recomputed per row, so storage stays constant.