Right-angled star triangle
Given a row count n, return a right-angled triangle of stars as an array of n strings, one per row. Row 1 holds a single *, row 2 holds two, and row n holds n of them. The left edge is flush: no row carries leading padding, so the stars of every row begin in the same column.
Examples
Example 1
- Input
- n = 5
- Output
* ** *** **** *****
Five rows widening by one star each time, so the last of them holds five.["*","**","***","****","*****"]
Example 2
- Input
- n = 1
- Output
*
One row, and row 1 holds one star.["*"]
The Code
function rightTriangle(n) {
const rows = [];
for (let row = 1; row <= n; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "*";
}
rows.push(line);
}
return rows;
}
rightTriangle(5);The first 19 calls, of 27. This one does not fit on a page.
Explanation
A row’s width is the row’s own number. Nothing carries from one row to the next, so the shape is decided by where the counting stops on each one.
- 1
rowis 1.linestarts as the empty string, and the inner loop runs whilecolis at mostrow— so once, appending one*.rows.push(line)stores the finished string.*0row=1rows.length=0
rows.push("*")
- 2
rowis 2, and the inner bound isrowrather than a number, so it moves with it: two passes,linebecomes"**".*0**1row=2rows.length=1
rows.push("**")
- 3
rowis 3 — three passes, three stars. Nothing is carried over from the row before, becauselineis declared inside the outer loop and starts empty again.*0**1***2row=3line=""
rows.push("***")
- 4
rowis 4, socolruns 1, 2, 3, 4 and four stars go on.*0**1***2****3row=4rows.length=3
rows.push("****")
- 5
rowis 5: five passes, five stars.row++then makes it 6, which failsrow <= n, so the outer loop ends and the five strings inrowsare handed back.*0**1***2****3*****4row=5rows.length=4
return rows → 5 rows
More like this
All star & number patterns examples (12) →- Inverted triangle Same triangle, counted downwards instead of up.
- Star pyramid Leading spaces do the centring; stars go up in odd numbers.
- Star diamond A pyramid, then the same pyramid upside down — minus the shared row.
- Hollow square Fill only the border — every interior cell is a space.
- Butterfly Two wings of stars with a gap between them that closes and reopens.
- Floyd’s triangle One counter that never resets, spilled across widening rows.