Pattern 1
EasySolid n x n square
Problem
Print a solid n x n square of stars 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
Two nested loops: the outer one picks a row, the inner one prints the characters of that row. Every pattern in this set is the same skeleton — only the inner loop's bounds and the character it prints change.
The trick
- Outer loop = rows, inner loop = columns. Fix that and the rest is arithmetic.
- Print the newline once per outer iteration, after the inner loop finishes.
rows5
Step 1 of 7. Solid square: every row prints n stars. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// * * * * *3// * * * * *4// * * * * *5// * * * * *6// * * * * *7 8for i in 1..n:9 for j in 1..n: print('* ')10 newlineInput
- grid
- 5 × 5
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.