DSA Factory
Free lessonsProgramming basics · Stage 8 · Loops inside loops · Step 2

Rows, then columns

Build a pattern of rows, where the inner loop writes the characters of one row. About 9 minutes.

A pattern, row by row

Think of drawing a staircase of # signs on squared paper. Row 1 has one sign, row 2 has two, row 3 has three. You draw one row at a time, and within each row you draw the signs from left to right.

That's two loops again. The outer loop goes through the rows. The inner loop goes through the columns of the current row, and it adds one sign per pass. The inner loop's length can depend on which row you are on.

Outer loop: the rows. Inner loop: the signs in one row.
In code
for row in range(1, n + 1):
    for col in range(row):
        ...    # one sign per pass
A staircase of 3 rows
#
0
1
2
row
row
1
line
#

Row 1: the inner loop runs once, adding one sign. The line is #, which goes into the list.

Move 1 of 4

Build one line, then keep it

A function can't print on squared paper, so we return the picture as a list of strings, one string per row. Make an empty list for the rows. In the outer loop, start an empty string for the current line, and let the inner loop add a sign to it on each pass.

When the inner loop ends, the line is finished, so add it to the list of rows. Start each new line empty, inside the outer loop, or the old signs carry over into the next row.

Make the empty line inside the outer loop, so each row starts fresh.
In code
rows = []
for row in range(1, n + 1):
    line = ""
    for col in range(row):
        line = line + "#"
    rows.append(line)
Quick check

A staircase has 4 rows: one sign in the first row, two in the second, and so on. How many signs are there in total?

  1. A10
  2. B16
  3. C4
Show the answer

10. 1 + 2 + 3 + 4 = 10.

Your problem

Staircase

Return a staircase as a list of n strings. The first string is "#", the second is "##", and so on, with the last string holding n # signs. If n is 0, return an empty list.

Example
n = 3 → ["#", "##", "###"]

0 ≤ n ≤ 50

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding