AlgoViz

Pattern 8

Easy

Inverted centred pyramid

Problem

Print an inverted centred star pyramid for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

The pyramid formulas run backwards: row i takes i-1 leading spaces and 2(n-i)+1 stars. Placing this directly under pattern 7 gives you the diamond.

The trick

  • Spaces = i - 1, stars = 2(n - i) + 1.
rows5

Step 1 of 7. Inverted centred pyramid: the star band shrinks each row. 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 i10  print '*' x (2(n-i)-1)11  newline

Input

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.