Pattern 4
EasyRow i repeats the number i
Problem
Print a triangle where row i prints the number i, i times 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
The inner loop still runs i times, but it prints the outer counter instead of its own. Comparing this with the previous pattern is the cleanest way to see that the row index and the column index are two independent pieces of information you can print either of.
The trick
- Print `i` (the row) rather than `j` (the column).
rows5
Step 1 of 7. Row i prints the number i, i times. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// 13// 2 24// 3 3 35// 4 4 4 46// 5 5 5 5 57 8for i in 1..n:9 for j in 1..i: print(i)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 / 2 2 / 3 3 3 / 4 4 4 4 / 5 5 5 5 5
Finished the walkthrough? Add it to your streak.