Loops & Number Patterns
EasyNested loops build rows and columns
Use one loop for the rows and another for what goes in each row — like drawing a shape one line at a time.
The idea
Pattern problems train loop control: the outer loop drives rows, the inner loop drives what's printed in each row. Relate the counters to the row index to shape triangles and pyramids.
n5
Step 1 of 22. The outer loop i drives the rows; the inner loop prints i stars in row i. Watch the triangle grow. n 5.
1/22
Optimal
timeO(rows·cols)spaceO(1)
Outer row, inner column.
1for (let i = 1; i <= n; i++) {2 let row = "";3 for (let j = 1; j <= i; j++) row += "*";4 print(row);5}Input
- grid
- 5 × 5
Memory
- n
- 5
- row
- —
Output
- printed rows
- —
- rows
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 4, rows of i stars
- Output:
- *\n**\n***\n****
- Explanation:
- The outer loop picks the row, the inner loop prints that row's stars. Row i gets exactly i of them.
Example 2
- Input:
- n = 3, centred pyramid
- Output:
- *\n ***\n*****
- Explanation:
- Each row prints n-i spaces then 2i-1 stars, which is the whole trick behind every centred pattern.
Finished the walkthrough? Add it to your streak.