Inverted star triangle
Given a row count n, return an inverted right-angled triangle of stars as an array of n strings. The first row holds n stars and every row after it holds one fewer, so the last row holds a single *. The left edge is flush: the rows all begin in the same column and lose their stars from the right.
Examples
Example 1
- Input
- n = 5
- Output
***** **** *** ** *
Five rows starting at five stars and losing one each time.["*****","****","***","**","*"]
Example 2
- Input
- n = 1
- Output
*
One row, which is both the widest and the narrowest, so it holds one star.["*"]
The Code
function invertedTriangle(n) {
const rows = [];
for (let row = n; row >= 1; row--) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "*";
}
rows.push(line);
}
return rows;
}
invertedTriangle(5);The first 17 calls, of 27. This one does not fit on a page.
Explanation
The widths are the growing triangle’s, 1 through n, handed out in the opposite order. Only the order the rows are counted in changes, so nothing inside a row has to.
- 1
rowstarts atnrather than 1, and the inner bound is stillrow, so the very first row is the widest: five passes, five stars.*****0row=5rows.length=0
rows.push("*****")
- 2
row--takes it to 4, which is still at least 1, so the outer loop runs again. The inner loop follows it down to four passes.*****0****1row=4rows.length=1
rows.push("****")
- 3
rowis 3. Only the direction of the outer count has changed — the body buildinglineis the same one the growing triangle uses.*****0****1***2row=3line=""
rows.push("***")
- 4
rowis 2, socolruns 1 and 2 and two stars go on.*****0****1***2**3row=2rows.length=3
rows.push("**")
- 5
rowis 1: one pass, one star.row--then makes it 0, which failsrow >= 1, so the loop ends on the narrowest row instead of the widest.*****0****1***2**3*4row=1rows.length=4
return rows → 5 rows
More like this
All star & number patterns examples (12) →- Star triangle The inner loop runs as far as the row number — that is the whole idea.
- 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.