Inverted Center-Aligned Pyramid Star Pattern in JavaScript

What You'll Learn
This program prints an inverted center-aligned pyramid. Stars decrease each row, while leading spaces increase to keep the pyramid centered.
Loop from i = rows down to 1. Print rows - i spaces, then print 2*i - 1 stars.
⭐ Pattern Output
When you run the program with rows = 5:
*********
*******
*****
***
*Complete JavaScript Program
Fixed rows = 5 version (reverse outer loop):
const rows = 5;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let s = 1; s <= rows - i; s++) line += " ";
for (let j = 1; j <= 2 * i - 1; j++) line += "*";
console.log(line);
}🧠 How It Works
Reverse outer loop
for (let i = rows; i >= 1; i--) starts at the wide row and shrinks i each time—the opposite direction of Program 5, same inner math.
Growing leading spaces
for (let s = 1; s <= rows - i; s++) line += " "; still uses rows - i; as i drops, the margin grows and the shape narrows.
Shrinking odd star block
for (let j = 1; j <= 2 * i - 1; j++) line += "*"; then console.log(line). Star counts step down 9, 7, 5, … when rows = 5.
Inverted pyramid
O(n²) output, O(1) extra space. Same line width as Program 5; the green glyph area scrolls horizontally on phones when rows is large.
💡 Tips for Enhancement
Try These
- Build rows with
" ".repeat(rows - i) + "*".repeat(2 * i - 1) - Compare with Program 5 to see how iteration direction flips the shape
- Try printing spaces between stars using
"* ".repeat(2 * i - 1).trimEnd() - Make a hollow inverted pyramid by printing only the border stars
- Change the symbol from
*to#or@
Avoid
- Using tabs for alignment (rendering differs across editors)
- Using even star counts (breaks centering symmetry)
- Printing trailing spaces after the stars (can look odd in some outputs)
- Mixing
with normal spaces (output becomes inconsistent) - Forgetting the line break after each row
Key Takeaways
Use a reverse loop: i = rows .. 1.
Row i prints rows - i leading spaces.
Then it prints 2*i - 1 stars (odd counts).
Spaces increase as stars decrease to keep centering.
Time complexity is O(n²) because printing dominates.
❓ Frequently Asked Questions
i decreases, 2*i - 1 produces fewer stars each row while rows - i produces more spaces." ".repeat(rows - i) + "*".repeat(2 * i - 1).n rows, since total printed characters are \(\Theta(n^2)\).Next: Inverted V Hollow
Continue to Program 7 to print an inverted V-shaped hollow star pattern.
Using the same 2*i - 1 formula, you can flip between a pyramid and an inverted pyramid just by changing the direction of the outer loop.
9 people found this page helpful
