Inverted Right-Angled Triangle Star Pattern in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Reverse Iteration

What You’ll Learn

The inverted right-angled triangle is the mirror of Program 1: same inner star loop, but the outer loop counts down so the widest line prints first. This tutorial covers reverse iteration, an equivalent forward-loop formula, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Wide first

First line has rows stars; each next line has one fewer down to 1.

Outer Loop

Countdown

for (let i = rows; i >= 1; i--) starts at the widest row.

Inner Loop

Same as P1

for (let j = 1; j <= i; j++) still prints exactly i stars.

Alt Formula

rows - i + 1

Forward outer loop with star count rows - i + 1 draws the same shape.

Live Preview

1–20 rows

Pick a row count and draw the inverted triangle instantly.

O(n²)

Complexity

Total stars = n(n+1)/2 - same count as Program 1.

Introduction

An inverted right-angled triangle shrinks by one * on each new line. With the right angle on the left, the console output looks like an upside-down staircase of stars.

Compared with Program 1, you keep the same j from 1 to i star loop, but run the outer loop from rows down to 1 so the first printed line is the widest.

Why it matters?

Reverse outer iteration is a tiny change with a big visual payoff. Pairing it with Program 1 is one of the fastest ways to read nested loops fluently.

Key Highlights

Countdown Outer

i runs rows1.

Same Inner Loop

Still print i stars with line += "*".

Two Formulations

Countdown i, or forward with rows - i + 1.

Same Complexity

Still O(n²) and n(n+1)/2 stars.

In short: for i from rows down to 1, append i stars with line += "*", then call console.log(line).

📝 Problem & Approach

Given a positive integer rows, print a left-aligned inverted right-angled triangle of * characters with rows lines.

JavaScript
// First 5 rows (conceptual shape)
// *****
// ****
// ***
// **
// *

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines (typically ≥ 1). First line has this many stars.
Printed outputtextLeft-aligned rows of *; line with outer index i has i stars.

Minimal workflow

Pseudocode
for i from rows down to 1:
    for j from 1 to i:
        append "*"
    console.log(line)

Approach comparison

ApproachIdeaBest for
Countdown outeri = rows..1, print i starsClearest “invert Program 1” story
Forward + formulai = 1..rows, print rows - i + 1 starsWhen you prefer ascending counters

⚡ Quick Reference

GoalPattern
Countdown rowsfor (let i = rows; i >= 1; i--)
Print i starsfor (let j = 1; j <= i; j++) line += "*"
End the rowconsole.log(line)
Forward equivalentfor (let j = 1; j <= rows - i + 1; j++)
One-line row shortcutconsole.log("*".repeat(i)) while counting down

📋 Program 1 vs Program 2 vs Forward Formula

Same star counts - different outer-loop direction (or bound).

Program 1
i = 1..rows

Stars grow: *, **, ***, …

This page
i = rows..1

Stars shrink: *****, ****, …, *

Forward alt
rows - i + 1

Ascending i, decreasing star count

Interview tip
name both

Countdown is clearer; formula shows bound flexibility

Context

When This Pattern Shows Up

Reach for the inverted triangle when teaching reverse outer bounds after Program 1.

  1. Right after Program 1

    Natural second lab: flip one loop, keep the rest.

  2. Reverse-iteration drills

    Practice i-- outer loops with a clear visual check.

  3. Bound-formula practice

    Rewrite with rows - i + 1 to separate “row number” from “star count.”

  4. Gateway to mirrors

    Lower halves of diamonds reuse the same countdown idea.

  5. Not a UI layout tool

    Terminal teaching pattern - not how you build app screens.

Key benefit: one-line change from Program 1 that locks in how outer-loop direction controls the picture.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the inverted triangle in the browser.

Try 5, 7, or 10. The first line will have that many stars.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - countdown outer loop, prompt input, and a forward-loop equivalent with "*".repeat(stars). Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print five rows by counting the outer loop down from 5.

Example 1 — Fixed rows = 5 (Countdown)

Classic reverse outer loop - the clearest invert of Program 1.

JavaScript
let rows = 5;

for (let i = rows; i >= 1; i--) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += "*";
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 5, the inner loop appends five stars. Then i becomes 4, 3, 2, and finally 1 - each time appending fewer stars. console.log(line) after the inner loop starts the next (shorter) row.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows with prompt and parseInt (validate with Number.isFinite in real apps).

JavaScript
let rows = parseInt(prompt("Enter the number of rows:"), 10);
if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a whole number of rows >= 1.");
} else {
  for (let i = rows; i >= 1; i--) {
    let line = "";
    for (let j = 1; j <= i; j++) {
      line += "*";
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same countdown core as Example 1; only the source of rows changes. Non-numeric input yields NaN with bare parseInt(prompt(), 10) - validate with Number.isFinite for safer labs.

⚡ Alternate Style

Same shape without counting the outer loop backward.

Example 3 — Forward Loop + rows - i + 1

Ascending i with a decreasing star count; uses "*".repeat(stars) for brevity.

JavaScript
let rows = 5;

for (let i = 1; i <= rows; i++) {
  const stars = rows - i + 1;
  console.log("*".repeat(stars));
}
Try it Yourself

How It Works

When i = 1, stars = 5; when i = 5, stars = 1. Same picture as the countdown version - useful when an interviewer asks for an ascending outer loop.

🧠 How the Algorithm Prints Rows

1

Set up

Set rows (fixed or from prompt). The first line will have rows stars.

Setup
2

Outer loop (countdown)

for (let i = rows; i >= 1; i--) starts at the widest row and counts down.

Row
3

Inner loop (stars)

for (let j = 1; j <= i; j++) prints exactly i stars with line += "*".

Stars
4

New line

console.log(line) ends the row before i decreases again.

Break
=

Inverted triangle

Total stars: n(n+1)/2 — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop value of i as it counts down, and count how many times the inner loop runs.

iInner j rangePrinted rowStars this row
41..4****4
31..3***3
21..2**2
11..1*1

Total star prints: 4 + 3 + 2 + 1 = 10 = 4×5/2 - same total as the upright triangle of height 4.

Use Cases

Where this inverted pattern (and reverse outer loops) shows up beyond the homework prompt.

1. Pair With Program 1

Show how one bound change flips the picture.

Example: side-by-side outputs for rows = 5.

2. Diamond Lower Halves

Countdown outer loops appear again in filled diamonds.

Example: Program 10 lower phase.

3. Bound Rewrites

Practice expressing star count as a formula of i.

Example: stars = rows - i + 1.

4. Character Substitution

Swap * for digits once the countdown works.

Example: print i instead of *.

5. Complexity Check

Same triangular total as the upright triangle.

Example: count stars for n = 10 → 55.

6. Input Validation Labs

Pair with input validation and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: say “same inner loop as Program 1, outer loop reversed” before coding - that is the whole design.

Advantages

Why this inverted pattern is a perfect second exercise.

  1. 1. Minimal Delta From Program 1

    Change one loop header and the picture flips - great for learning.

  2. 2. Instant Visual Feedback

    Wrong outer direction or bound shows up as the upright triangle.

  3. 3. Two Valid Stories

    Countdown or forward formula - both are interview-friendly.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: lead with the countdown story for clarity, then mention the rows - i + 1 rewrite as a follow-up.

Usage Tips

Small habits that keep inverted-triangle code clean.

  1. 1. Start From rows, Not a Literal

    Write i = rows so changing the height does not require editing the loop header twice.

  2. 2. Keep console.log(line) Outside

    Only call console.log(line) after the inner star loop finishes.

  3. 3. Wrap parseInt(prompt(), 10) in try/except

    Avoid crashes when the user types letters instead of a number.

  4. 4. Know Both Formulations

    Countdown and rows - i + 1 - pick one, mention the other.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

Pro Tip: if the output grows like Program 1, your outer loop is still counting up - flip it or switch the star bound.

Common Pitfalls

Mistakes that commonly break inverted star triangles.

  1. 1. Leaving the Outer Loop Ascending

    You reprint Program 1 instead of the inverted shape.

    → Use for (let i = rows; i >= 1; i--) or change the star bound.

  2. 2. console.log(line) Inside the Inner Loop

    Each star lands on its own line - a column, not a triangle.

    → Use line += "*" for stars; console.log(line) only after the inner loop.

  3. 3. Hard-Coding 5 in the Loop

    Changing rows no longer updates the outer bound.

    → Always start from the rows variable.

  4. 4. Off-by-One on Forward Formula

    Using rows - i instead of rows - i + 1 drops the last star on each line.

    → First forward row needs rows stars: rows - 1 + 1.

  5. 5. Blind parseInt(prompt(), 10)

    Letters or empty input throw NaN.

    → Catch NaN and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single star

Output is just * - same as Program 1 for n = 1.

rows = 0

Empty pattern

Outer loop never runs - print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Wide first line

First line has n stars - fine for labs; noisy for huge n.

Bad input

Non-numeric ReadLine

parseInt(prompt(), 10) yields NaN - validate first.

First line

i == rows

Remember: the first printed line uses the largest i, not index 1.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Flip back to Program 1

  • Change only the outer loop to count up
  • Confirm the staircase grows again

2. Rewrite with forward formula

  • Use rows - i + 1 stars
  • Match Example 3’s output

3. Safe input loop

  • Validate input until rows >= 1
  • Then draw the inverted triangle

4. Right-aligned next

  • Add leading spaces before stars
  • Continue with Program 3

Notes

  • Same total. Star count is still n(n+1)/2 - only print order changes.
  • The inner loop is identical to Program 1; reverse the outer loop to invert.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single star.
  • Next up: right-aligned triangles add a space loop before the stars.

Quick Takeaway: outer loop counts down from rows, inner loop prints i stars, then break the line - that is the inverted triangle.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Countdown nested loops (Examples 1–2)O(rows²)O(1)
Forward + "*".repeat (Example 3)O(rows²)O(rows) temporary per row string
Wrap Up

🎉 Conclusion

The inverted right-angled triangle is Program 1 with a reversed outer loop: widest line first, then one fewer star each row. Master the countdown version, then know the rows - i + 1 rewrite for ascending counters.

Practice the three examples above, then continue to the right-aligned triangle for leading spaces.

Outer loop rows1, inner loop prints i stars - keep line += "*" and console.log(line) separated, and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Explain “Program 1 but outer loop reversed” before coding
  • Start the outer loop from rows, not a hard-coded number
  • Use line += "*" for stars and console.log(line) after each row
  • Know the rows - i + 1 alternate formulation
  • State O(n²) time when asked about complexity

❌ Don’t

  • Keep an ascending outer loop and expect an inverted shape
  • Call console.log(line) inside the inner star loop
  • Use rows - i when you meant rows - i + 1
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this inverted pattern

Print the upside-down triangle the beginner-friendly way.

5
Core concepts
02

Outer loop

rows → 1

Code
* 03

Inner loop

Same as Program 1

Code
f 04

Alt formula

rows - i + 1

Option
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The outer loop runs i from rows down to 1. For each i, the inner loop appends i stars. The first output line uses i equal to rows so it is the longest; each later line has a smaller i, so the triangle points downward.
Program 1 uses for (let i = 1; i <= rows; i++) so stars grow. This program uses for (let i = rows; i >= 1; i--) so stars shrink. The inner loop still runs j from 1 to i.
Yes. Use for (let i = 1; i <= rows; i++) and append (rows - i + 1) stars in the inner loop. Both styles produce the same shape.
line += '*' stays on the same row with no newline between stars. console.log(line) ends the row after the inner loop finishes.
O(n^2) for n rows. Total stars are still n(n+1)/2, same as the upright triangle.
Yes. console.log('*'.repeat(i)) prints a full row in one call while i counts down.
Use parseInt(prompt(), 10) and check Number.isFinite so bad input does not produce NaN rows.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

This inverted triangle uses the same inner loop as Program 1 - only the outer loop direction changes. Total stars stay n(n+1)/2, so complexity is still O(n²).

Continue to Right-Aligned Triangle

Add a leading-space loop so the right angle sits on the right edge.

Program 3 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful