Pattern 7
EasyCentred star pyramid
Problem
Print a centred star pyramid for a given size n.
Use one loop for the rows and another for what goes in each row to draw the shape.
The idea
A centred pyramid needs two inner loops per row: one that prints the leading spaces and one that prints the stars. Row i gets n-i spaces then 2i-1 stars, which keeps every row the same total width so the pyramid stays centred.
The trick
- Spaces = n - i, stars = 2i - 1; those two formulas produce every centred pyramid.
- Total width is always 2n - 1, which is what makes the centre line up.
rows5
Step 1 of 7. Centred pyramid: leading spaces, then an odd number of stars. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// *3// ***4// *****5// *******6// *********7 8for i in 0..n-1:9 print ' ' x (n-1-i)10 print '*' x (2i+1)11 newlineInput
- grid
- 5 × 9
Memory
- rows
- 5
Output
- printed rows
- —
- rows
- 5
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- n = 5
- Output:
- ★ / ★ ★ ★ / ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ ★ ★
Finished the walkthrough? Add it to your streak.