Pattern 3
EasyNumber triangle 1..i per row
Problem
Print a number triangle where row i prints 1..i 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
Same triangle shape, but instead of a constant star the inner loop prints its own counter. The loop variable is the output, which is the simplest example of a pattern where position determines content.
The trick
- Print `j` rather than a star; the shape logic is unchanged.
rows5
Step 1 of 7. Number triangle: row i prints 1..i. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// 13// 1 24// 1 2 35// 1 2 3 46// 1 2 3 4 57 8for i in 1..n:9 for j in 1..i: print(j)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:
- 1 / 1 2 / 1 2 3 / 1 2 3 4 / 1 2 3 4 5
Finished the walkthrough? Add it to your streak.