Right-Aligned Reverse Pyramid in JavaScript

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

What You’ll Learn

Each row is a reverse suffix (A, BA, CBA, …) padded on the left so the letters line up on the right in a fixed-width column. This is the same code > i idea as the left half of Program 19, but without the second mirror loop. Compare Program 2 (reverse, left-aligned). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Right-aligned reverse

Growing reverse suffixes sit on the right of a fixed width.

Outer Loop

Row peak

i walks A..top so the visible suffix grows each row.

Inner Scan

Fixed width

code always walks top down to A for every row.

Pad Rule

code > i

Print a space while above the peak; then print letters.

Live Preview

Top letter

Pick A–J and draw the right-aligned pyramid instantly.

O(n²)

Complexity

n rows × n columns per fixed-width scan.

Introduction

A right-aligned reverse alphabet pyramid keeps every row the same width and fills the left with spaces until the reverse suffix begins — so A, BA, CBA, … line up on the right edge.

In JavaScript you solve it with nested loops and ord/chr: outer i grows the peak, inner code scans top..A, and code > i decides space vs letter.

Why it matters?

It combines three beginner skills: fixed-width scans, leading-space padding, and descending letter order — the same toolkit used for many right-aligned pyramids.

Key Highlights

Fixed Width

Every row scans top..A columns.

Leading Spaces

code > i pads until the suffix starts.

Reverse Suffix

Descending code prints BA, CBA, DCBA…

Growing Peak

Outer i from A to top lengthens the suffix.

In short: for each peak i, scan top..A - append a space while code > i, otherwise append String.fromCharCode(code), then call console.log(line).

📝 Problem & Approach

Given a top letter (like E), print a right-aligned pyramid of reverse alphabet suffixes.

JavaScript
# Classic sample (top = E; leading spaces matter)
#     A
#    BA
#   CBA
#  DCBA
# EDCBA

Inputs & Outputs

ItemTypeDescription
topstr / intHighest letter (e.g. E) or top.charCodeAt(0). Line width = top - 'A' + 1.
Printed outputtextRight-aligned reverse suffixes with leading spaces.

Minimal workflow

Pseudocode
for i from base to top:
    line = ""
    for code from top down to base:
        if code > i: line += " "
        else: line += String.fromCharCode(code)
    console.log(line)

Approach comparison

ApproachIdeaBest for
Fixed-width scanSpace-or-letter in each columnMatching this classic sample
Explicit pad + suffixPrint spaces, then i..A reverseClearer reading / teaching rewrite

⚡ Quick Reference

GoalPattern
Row peaksfor (let i = base; i <= top; i++)
Fixed scanfor (let code = top; code >= base; code--)
Pad vs letterline += (code > i ? " " : String.fromCharCode(code))
End the rowconsole.log(line)
Left-aligned reverseSee Program 2
Add right mirrorSee Program 19

📋 Space vs Letter vs console.log

Same fixed-width row — different roles on each column.

line += " "
code > i

Leading pads that create right alignment

line += letter
code <= i

Reverse suffix letters for the current peak

code--
E..A

Inner direction makes BA, CBA, DCBA…

console.log
break

Ends the row after the full width scan

Context

When This Pattern Shows Up

Reach for this when teaching right alignment with reverse letter fills.

  1. After Program 19

    Keep one half of the dual scan — the pad-and-suffix idea alone.

  2. Alignment drills

    Practice leading spaces on a fixed-width console line.

  3. Compare with Program 2

    Same reverse letters; left-aligned vs right-aligned layout.

  4. Before diamond labs

    Padding intuition helps when you later center rows.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one condition (code > i) turns a flat reverse scan into a right-aligned pyramid.

🔮 Live Preview

Enter a top letter from A to J and draw the right-aligned reverse pyramid in the browser.

Try E (classic sample) or D (smaller). Use a single letter A–J for a readable preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed A–E, user-chosen top letter, and an explicit pad-then-suffix rewrite. Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print five right-aligned reverse rows with a fixed-width scan.

Example 1 — Fixed Top E

Outer i is the row peak. Inner code sweeps E down to A and appends a space until it reaches i.

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

for (let i = base; i <= top; i++) {
  let line = "";
  for (let code = top; code >= base; code--) {
    line += (code > i) ? " " : String.fromCharCode(code);
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = "C".charCodeAt(0), columns E and D append spaces; then C, B, A append → ··CBA. When i = "E".charCodeAt(0), every column is a letter → EDCBA.

📈 Practical Variant

Let the user choose the last letter.

Example 2 — Top Letter Input

The pattern keeps the line width fixed to the chosen top letter. Prefer validating a single A–Z character from prompt().trim().toUpperCase() in real apps.

JavaScript
const raw = (prompt("Enter the top letter (like E):") || "").trim().toUpperCase();
const top = raw ? raw.charCodeAt(0) : "E".charCodeAt(0);
const base = "A".charCodeAt(0);

for (let i = base; i <= top; i++) {
  let line = "";
  for (let code = top; code >= base; code--) {
    line += (code > i) ? " " : String.fromCharCode(code);
  }
  console.log(line);
}
Try it Yourself

How It Works

Same code > i rule; only the shared bounds follow top. With top = "D".charCodeAt(0) you get a 4-column right-aligned pyramid.

⚡ Explicit Style

Same shape with separate pad and suffix loops.

Example 3 — Pad Spaces, Then Reverse Suffix

Often clearer to read: append leading spaces first, then letters from the peak down to A.

JavaScript
const top = "E".charCodeAt(0);
const base = "A".charCodeAt(0);
const width = top - base + 1;

for (let i = base; i <= top; i++) {
  const letters = i - base + 1;
  const pad = width - letters;
  let line = "";

  for (let p = 0; p < pad; p++) {
    line += " ";
  }
  for (let ch = i; ch >= base; ch--) {
    line += String.fromCharCode(ch);
  }

  console.log(line);
}
Try it Yourself

How It Works

Peak i needs i - base + 1 letters and width - letters leading spaces. The suffix loop appends String.fromCharCode(i) down to A - same visual pyramid as the scan version.

🧠 How the Algorithm Prints Rows

1

Outer loop chooses the row peak

i moves from "A".charCodeAt(0) to top, increasing the visible suffix each time.

Rows
2

Inner loop scans the full width

code runs from top down to "A".charCodeAt(0), giving a fixed-width line.

Width
3

Spaces create right alignment

If code > i append a space; otherwise append String.fromCharCode(code). Leading spaces push the suffix to the right edge.

Align
4

New line

console.log(line) ends the row so the next peak starts fresh.

Break
=

Fixed width, growing suffix

For n letters, total work is O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — top E

Trace each peak i and how many pads vs letters print.

iLeading spacesSuffixPrinted row
A4A····A
B3BA···BA
C2CBA··CBA
D1DCBA·DCBA
E0EDCBAEDCBA

Pad count is top - i (as char distance). Each row still scans 5 columns.

Use Cases

Where this right-aligned reverse pyramid shows up beyond the homework prompt.

1. Alignment Practice

Clearest alphabet demo of leading spaces on a fixed width.

Example: print . instead of spaces while debugging.

2. Pair with Program 2

Same reverse letters — left-aligned vs right-aligned.

Example: print both for top E side by side.

3. Half of Program 19

This scan is the left half of the mirrored-gap pattern.

Example: add a right mirror pass next.

4. Explicit Pad Rewrite

Teach pad count separately from the reverse suffix (Example 3).

Example: compare scan vs pad+suffix outputs.

5. Complexity Intuition

Fixed-width scans make O(n²) easy to count.

Example: 5 rows × 5 columns = 25 writes.

6. Char Validation

Practice reading and validating a single top letter.

Example: reject empty strings and non A–Z input.

Pro Tip: say “pad while above the peak, then print reverse letters” before coding — that story prevents flipped alignment.

Advantages

Why this pattern earns a spot after left-aligned reverse triangles.

  1. 1. Instant Visual Feedback

    Missing pads or a flipped inner loop show up as a broken pyramid immediately.

  2. 2. Two Clear Rewrites

    Fixed-width scan or explicit pad/suffix loops teach the same shape.

  3. 3. Builds Toward Program 19

    Master one half before adding the mirrored right ramp.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop variables.

Pro Tip: learn the classic scan version first; treat the explicit pad/suffix rewrite as a clarity upgrade afterward.

Usage Tips

Small habits that keep right-aligned reverse pyramids clean.

  1. 1. Keep a Fixed Inner Width

    Always scan top..A so shorter suffixes stay right-aligned.

  2. 2. Use Spaces, Not Tabs

    Tabs change width by editor settings and ruin alignment.

  3. 3. Validate Letter Input

    Require a single A–Z character; empty input breaks top_ch[0].

  4. 4. Debug with Dots

    Temporarily print . instead of spaces to count the gap.

  5. 5. Dry-Run Peak C

    Trace two spaces then CBA on paper before coding larger tops.

Pro Tip: if letters sit on the left with trailing spaces, you almost certainly flipped the code > i condition.

Common Pitfalls

Mistakes that commonly break right-aligned reverse alphabet pyramids.

  1. 1. Flipping the Pad Condition

    Using code < i for spaces left-aligns or garbles the suffix.

    → Print a space when code > i.

  2. 2. Scanning Upward

    Going A..top prints forward letters (AB, ABC) instead of reverse suffixes.

    → Keep code descending from top to A.

  3. 3. Tabs Instead of Spaces

    Alignment depends on the editor’s tab size.

    → Always print a single space character.

  4. 4. Blind top_ch[0]

    Empty or multi-character input can throw or pick the wrong char.

    → Read a string, check length, take [0], validate A–Z.

  5. 5. console.log(line) Mid-Scan

    Breaks the row into one character per line.

    → Call console.log(line) only after the full width finishes.

Edge Cases

Check these inputs before calling the solution done.

top = A

Single letter

Output is just A (no pads).

top = E

Classic sample

Five rows ending in EDCBA.

top = D

Smaller pyramid

Four columns; last row DCBA.

Past Z

Invalid top

Reject or cap so indices stay in A–Z.

Bad input

Empty input

top_ch[0] fails on empty tokens — validate first.

Pad mark

. instead of space

Same loops; only the pad character changes.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Drop the padding

  • Print reverse suffixes left-aligned
  • Compare with Program 2

2. Add the right mirror

3. Explicit pad version

  • Use pad count + suffix (Example 3)
  • Confirm output matches the scan

4. Continue to Program 21

  • Diamond alphabet with alternating stars
  • See Program 21

Notes

  • Fixed width. Every row scans the same top..A columns.
  • code > i creates leading spaces; descending code creates reverse suffixes.
  • This is Program 19’s left half without the right mirror pass.
  • Prefer spaces over tabs for stable monospace alignment.

Quick Takeaway: scan top..A, pad while above the peak, print the reverse suffix, then break the line — that is the whole pyramid.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed-width scan (Examples 1–2)O(n²)O(1)
Explicit pad + suffix (Example 3)O(n²)O(1)

With n = top − ‘A’ + 1, each of n rows scans n columns (or pads + letters totaling n), so work is O(n²).

Wrap Up

🎉 Conclusion

The right-aligned reverse alphabet pyramid is a small nested-loop exercise with lasting payoff: fixed-width scans, leading-space padding, and descending letter fills. Master the classic ····A…EDCBA sample, then try user input and the explicit pad rewrite.

Practice the three examples above, then continue to Program 21’s diamond alphabet pattern with alternating stars.

Scan top..A, append spaces while code > i, append letters otherwise, and break only after the scan.

💡 Best Practices

✅ Do

  • Scan a fixed top..A width every row
  • Print spaces when code > i
  • Keep the inner loop descending for reverse suffixes
  • Validate a single A–Z character on input
  • State O(n²) when asked about complexity

❌ Don’t

  • Flip code > i unless you want left alignment
  • Use tabs for padding
  • Call console.log(line) inside the column scan
  • Assume empty input is safe for top_ch[0]
  • Scan upward if you want BA, CBA, DCBA…

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

Print the right-aligned reverse alphabet pyramid the beginner-friendly way.

5
Core concepts
W 02

Width

Always top..A

Code
> 03

Pad

code > i → space

Code
04

console.log

Ends each scan

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

code walks from E down to A. While code is above the current row peak i, append spaces; once code reaches i and below, append letters. That pushes the visible suffix (like CBA) to the right of a fixed-width line.
Because we append leading spaces for columns where code > i. That pushes the letters to the right and forms a right-aligned pyramid.
Descending code prints letters in reverse order (BA, CBA, DCBA). If code went upward, you would get AB, ABC, ABCD instead.
Update the loop bounds so the outer loop runs up to 'H'.charCodeAt(0) and the inner scan starts from 'H'.charCodeAt(0) down to 'A'.charCodeAt(0).
line += ch or line += ' ' stays on the same conceptual row for each cell. console.log(line) ends the row after the fixed-width scan finishes.
Program 2 prints reverse prefixes left-aligned (E, ED, EDC...). This pattern prints reverse suffixes right-aligned with leading spaces (A, BA, CBA...).
O(n^2) for n letters because there are n rows and each row scans n positions.
Use prompt().trim().toUpperCase(), take the first character, require A-Z, and reject empty tokens. Cap at Z if you only want alphabetic ranges.

Did you Know? 🔊

Each line has fixed width (five columns for AE). Scanning from top down to A, letters above the row peak turn into spaces, so the visible suffix (CBA, DCBA, …) sits on the right.

Continue to Alphabet Pattern 21

Next up: diamond-style alphabet rows that alternate letters and stars.

Program 21 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