Reverse Pyramid (Right-aligned)

Beginner
⏱️ 9 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Two inner loops

What You'll Learn

This pattern prints a right-aligned triangle where each row starts from E and goes down to the row letter. We use one loop to print leading blanks and another loop to print letters in descending order.

⭐ Pattern Output

Output
        E
      E D
    E D C
  E D C B
E D C B A
1

Node.js / console version

Build each row with blanks and letters, then log it.

JavaScript
const A = "A".charCodeAt(0);
const top = "E".charCodeAt(0);

for (let i = top; i >= A; i--) {
  let line = "";
  for (let j = A; j < i; j++) line += "  ";
  for (let j = top; j >= i; j--) line += String.fromCharCode(j) + " ";
  console.log(line.trimEnd());
}
2

Browser version (document.write + div)

Matches the reference: fixed-width cells for alignment.

HTML
<!DOCTYPE html>
<html>
<head>
  <style>
    div.cell {
      display: inline-block;
      text-align: center;
      width: 18px;
    }
  </style>
</head>
<body>
<script>
  const A = 65;
  const top = 69;
  for (let i = top; i >= A; i--) {
    for (let j = A; j < i; j++) document.write(\"<div class=\\\"cell\\\"></div>\");
    for (let j = top; j >= i; j--) document.write(\"<div class=\\\"cell\\\">\" + String.fromCharCode(j) + \"</div>\");
    document.write(\"<br>\");
  }
</script>
</body>
</html>

🧠 How It Works

1

Outer loop: i from E down to A

Each next row shifts right and prints one more letter.

5 rows
2

Indent: j from A to i - 1

Print two-space (or empty cell) padding so lower rows start further right.

Padding
3

Letters: j from E down to i

Print the descending run E, D, …, i with a space after each character.

Run
=

Right-shifting triangle

Padding grows while the printed run expands, producing a slanted triangle.

Key Takeaways

1

Outer loop counts down from E to A.

2

First inner loop prints blanks to right-align.

3

Second inner loop prints E..i in reverse.

4

Time complexity: O(n²).

❓ Frequently Asked Questions

They act like fixed-width spaces. HTML collapses regular whitespace, so empty cells keep the pyramid aligned.
Yes. Use const A = "a".charCodeAt(0) and const top = "e".charCodeAt(0).
For \(n\) rows, each row prints up to \(n\) cells, so it’s O(n²).

Next up

Continue with the next alphabet program.

Next: Program 24 →
Did you know?

Using fixed-width cells in HTML is often simpler than mixing spaces and &nbsp; when building aligned patterns.

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.

10 people found this page helpful