Right-Aligned Alphabet Pyramid in JavaScript

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

What You’ll Learn

Right-align the pyramid by printing a shrinking number of leading spaces, then printing letters from A up to the current row letter (restarting each row). Because we append letters using String.fromCharCode(k).padStart(2, " "), use a monospace font if you want the right edge to look perfect. Compare Program 22 (right-aligned sequential stream) and Program 16 (centered). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Growing prefixes

A, A B, A B C, … A B C D E.

Leading Pads

Shrink spaces

Print top - i spaces so rows share a right edge.

Restart A

Each row

Letters always run A..i — not a k++ stream.

Width 2

{0,2}

Fixed-width letter cells for even columns.

Live Preview

Top letter

Pick a top letter (A–F) and draw the pyramid.

O(n²)

Complexity

Pads + letters per row scale with n.

Introduction

A right-aligned alphabet pyramid prints growing prefixes of the alphabet (A, A B, A B C, …) pushed to the right with leading spaces so every row shares the same right edge.

In JavaScript you solve it with nested loops over letter codes: shrink the pad count, then append A..i with String.fromCharCode(k).padStart(2, " ") formatting.

Why it matters?

It combines padding math with per-row letter prefixes — the classic right-aligned triangle before sequential streams or centering.

Key Highlights

Pads First

Shrink leading spaces per row.

A..i

Restart letters every row.

Right Edge

All rows share the same end.

vs Stream

Not Program 22’s continuous k++.

In short: for each row letter i, append spaces while j > i, then append A..i with padStart(2, " "), then call console.log(line).

📝 Problem & Approach

Given a top letter (or fixed E), print a right-aligned pyramid of alphabet prefixes ending at that letter.

JavaScript
// Five rows (monospace; leading spaces + width-2 letters)
//     A
//    A B
//   A B C
//  A B C D
// A B C D E

Inputs & Outputs

ItemTypeDescription
topcharLast row letter (e.g. E). Row count = top - 'A' + 1.
Printed outputtextRight-aligned prefixes A..i with leading spaces.

Minimal workflow

Pseudocode
for i from base to top:
    line = ""
    for j from top down while j > i:
        line += " "
    for k from base to i:
        line += String.fromCharCode(k).padStart(2, " ")
    console.log(line)

Approach comparison

ApproachIdeaBest for
Char loops (classic)Pad top..i+1; letters A..iMatching this sample
Int row indexPad n-row; letters by indexWhen you prefer int counters

⚡ Quick Reference

GoalPattern
Outer rowsfor (let i = base; i <= top; i++)
Leading padsfor (let j = top; j > i; j--) line += " "
Lettersfor (let k = base; k <= i; k++) line += String.fromCharCode(k).padStart(2, " ")
End rowconsole.log(line)
Sequential streamSee Program 22

📋 Pad vs Letters vs console.log

Same row - three roles that build the right-aligned pyramid.

line += " "
pad

Leading spaces that shrink each row

padStart(2)
A..i

Prefix letters restarting from A

i grows
grow

Each row adds one more letter on the right

console.log
break

Ends the row after pads + letters

Context

When This Pattern Shows Up

Reach for this when teaching leading-space alignment with per-row alphabet prefixes.

  1. Classic triangle labs

    First right-aligned alphabet pyramid many courses assign.

  2. Compare with Program 22

    Same right edge idea; prefixes vs continuous stream.

  3. Before centering

    Step up to Program 16 after pads feel natural.

  4. Format-width drills

    Practice String.fromCharCode(k).padStart(2, " ") letter cells in monospace output.

  5. Not a UI layout tool

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

Key benefit: shrinking leading spaces while restarting A..i is the clearest way to teach right-aligned alphabet prefixes.

🔮 Live Preview

Choose a top letter from A to F and draw the right-aligned alphabet pyramid in the browser (monospace).

Try E (classic sample) or C (three rows). Preview allows A–F.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed A–E, user-chosen top letter, and an int-index 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 prefix rows from A through E.

Example 1 — Fixed A–E

First append leading spaces, then append letters A..i using padStart(2, " ").

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

for (let i = base; i <= top; i++) {
  let line = "";
  for (let j = top; j > i; j--) {
    line += " ";
  }
  for (let k = base; k <= i; k++) {
    line += String.fromCharCode(k).padStart(2, " ");
  }
  console.log(line);
}
Try it Yourself

How It Works

When i is 'C', two leading spaces append, then letters A B C via padStart(2, " "). The next row pads once and prints through D, keeping the right edge fixed.

📈 Practical Variant

Let the user choose the last letter (like E).

Example 2 — Top Letter Input

The pattern prints up to that row. Use prompt().trim().toUpperCase() and validate a single A–Z character in real apps.

JavaScript
let topCh = prompt("Enter top letter (like E):");
topCh = (topCh || "").trim().toUpperCase();
if (topCh.length !== 1 || !/^[A-Z]$/.test(topCh)) {
  console.log("Please enter a single letter.");
} else {
  const base = "A".charCodeAt(0);
  const top = topCh.charCodeAt(0);

  for (let i = base; i <= top; i++) {
    let line = "";
    for (let j = top; j > i; j--) {
      line += " ";
    }
    for (let k = base; k <= i; k++) {
      line += String.fromCharCode(k).padStart(2, " ");
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same pad + prefix rules; only the shared top letter changes. Pad count is always top - i spaces.

⚡ Int Style

Same shape with integer row and column indexes.

Example 3 — Int Row Index

Often clearer if you think in row numbers: pad n - row spaces, then print row letters from A.

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

for (let row = 1; row <= n; row++) {
  let line = "";
  for (let s = 0; s < n - row; s++) {
    line += " ";
  }
  for (let L = 0; L < row; L++) {
    line += String.fromCharCode(base + L).padStart(2, " ");
  }
  console.log(line);
}
Try it Yourself

How It Works

Row 1 prints one letter; row 5 prints five. Pad count is n - row; letter L is String.fromCharCode(base + L).

🧠 How the Algorithm Prints Rows

1

Pick the row letter

Outer i runs from A to E (or your chosen top).

Rows
2

Print leading spaces

Loop j = E..(i+1) prints one space per step, making the pyramid right-aligned.

Pad
3

Print letters A..i

Loop k = A..i appends each letter in a 2-character field using String.fromCharCode(k).padStart(2, " ").

Letters
4

New line

console.log(line) ends the row so the next lower pad count can grow the prefix.

Break
=

Right edge stays fixed

Each row does O(n) work for padding plus letters, so total is O(n²).

🔎 Worked Walkthrough — Top = E

Trace each row’s pad count, letter prefix, and printed line.

iPad spacesLettersPrinted row
A4A····A
B3A B···A B
C2A B C··A B C
D1A B C D·A B C D
E0A B C D EA B C D E

Pad count = top - i. Letters always restart at A.

Use Cases

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

1. Padding Labs

Clearest demo of shrinking leading spaces for right alignment.

Example: remove pads once and see a left-aligned triangle.

2. Pair with Program 22

Same right edge — prefixes vs continuous letter stream.

Example: print both for top = E side by side.

3. Char Loop Practice

Outer and inner loops over ascending char ranges.

Example: rewrite with int indexes (Example 3).

4. Format Width Practice

Use String.fromCharCode(k).padStart(2, " ") so letter columns stay even.

Example: try plain Write(k) and compare spacing.

5. Bridge to Centering

After right-align, add more pads for a centered look.

Example: see Program 16.

6. Bridge to Program 28

Next pattern builds a symmetric decreasing alphabet square.

Example: continue to Program 28.

Pro Tip: say “fewer spaces, then A through the row letter” before coding - that story prevents a continuous k++ stream by mistake.

Advantages

Why this pattern earns a spot early in the alphabet-pattern series.

  1. 1. Instant Visual Feedback

    Wrong pad counts or continuous streams show up immediately.

  2. 2. Two Clear Rewrites

    Char loops or int indexes teach the same shape.

  3. 3. Pad Practice

    A natural place to learn leading-space alignment.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop variables.

Pro Tip: learn the classic char-loop version first; treat the int-index rewrite as a clarity option afterward.

Usage Tips

Small habits that keep right-aligned prefix pyramids clean.

  1. 1. Restart Letters Each Row

    Always append A..i — do not keep a running k++ for this pattern.

  2. 2. Shrink Pads as i Grows

    Pad count is top - i; last row has zero pads.

  3. 3. Validate Top Letter Input

    Require a single A–Z character; normalize case if needed.

  4. 4. Use a Monospace Font

    Proportional fonts make String.fromCharCode(k).padStart(2, " ") columns look uneven.

  5. 5. Keep Pad Width Consistent

    Mixing one-space and two-space pads breaks the right edge.

Pro Tip: if rows look like A, B C, D E F, you wrote Program 22’s stream instead of restarting at A.

Common Pitfalls

Mistakes that commonly break right-aligned alphabet prefix pyramids.

  1. 1. Using a Continuous k++ Stream

    Rows become A, B C, D E F… instead of A, A B, A B C.

    → Restart letters from A on every row.

  2. 2. Wrong Pad Condition

    Using j >= i or the wrong bound leaves uneven right edges.

    → Pad while j > i from top downward.

  3. 3. Proportional Font Preview

    Columns look uneven even when the code is correct.

    → View output in a monospace terminal/font.

  4. 4. Blind letter conversion on bad input

    Empty lines or multi-character input break letter logic or use only the first char.

    → Validate a single A–Z letter after trim().toUpperCase().

  5. 5. Mixing Pad Widths

    Switching between one- and two-space pads breaks the right edge.

    → Keep pad characters consistent for the whole program.

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 through A B C D E.

top = C

Smaller pyramid

Three rows (Example 2).

Lowercase

Case mismatch

Normalize with .upper() if needed.

Bad input

Empty / multi-char

Validate before calling charCodeAt(0).

No pads

Left-aligned variant

Skip the pad loop for a left triangle.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Drop the pads

  • Print left-aligned A, A B, A B C…
  • Compare alignment with the sample

2. Switch to a stream

  • Use continuous k++ instead of A..i
  • Compare with Program 22

3. Center the pyramid

4. Continue to Program 28

  • Symmetric decreasing alphabet square
  • See Program 28

Notes

  • Prefixes. Each row restarts at A and grows through the row letter.
  • Leading spaces shrink as the prefix grows so the right edge stays fixed.
  • String.fromCharCode(k).padStart(2, " ") keeps letter columns even in monospace terminals.
  • Unlike Program 22, there is no running letter counter across rows.

Quick Takeaway: print shrinking leading spaces, then letters A..i with width 2, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Char pad + letters (Examples 1–2)O(n²)O(1)
Int row index (Example 3)O(n²)O(1)

Each of n rows does O(n) pad + letter work, so total work is O(n²).

Wrap Up

🎉 Conclusion

The right-aligned alphabet pyramid is a small nested-loop exercise with lasting payoff: shrinking leading spaces and per-row prefixes from A. Master the classic A…E sample, then try user input and the int-index rewrite.

Practice the three examples above, then continue to Program 28’s symmetric decreasing alphabet square.

Pad while j > i, print A..i with width 2, keep pads consistent, then break the line.

💡 Best Practices

✅ Do

  • Restart letters from A on every row
  • Shrink leading spaces as the prefix grows
  • View String.fromCharCode(k).padStart(2, " ") output in a monospace font
  • Validate a single A–Z top letter for input variants
  • State O(n²) when asked about complexity

❌ Don’t

  • Use a continuous k++ stream for this pattern
  • Mix pad widths across rows
  • Assume proportional fonts will align columns
  • Skip validating top-letter input
  • Call console.log(line) inside the pad or letter loop

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

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

5
Core concepts
A 02

Letters

Restart each row

Code
2 03

Width

{0,2} cells

Code
04

console.log

Ends each row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The first inner loop appends (top - i) leading spaces, fewer on each lower row, so the letter block ends at the same right edge.
Width-2 formatting prints each letter in an even column so the output matches the spaced layout (best viewed in a monospace font).
Program 22 uses a continuous counter across all rows. Program 27 restarts letters from A on every row and uses leading spaces to push rows to the right.
Remove the leading-space loop and append letters directly from A to the row letter.
O(n^2) for n rows because each row prints O(n) spaces plus O(n) letters.
Read a line with prompt(), trim it, call .toUpperCase(), require a single A-Z character, and reject empty or multi-character input.
Program 16 centers the pyramid with more padding. This pattern only right-aligns by shrinking leading spaces while restarting A..i each row.
Yes. Pad n - row spaces, then append row letters as String.fromCharCode(base + L). Example 3 on this page shows that style.

Did you Know? 🔊

Leading padding: for each row letter i, the loop appends top - i spaces. Then the letter loop appends A through i using String.fromCharCode(k).padStart(2, " ") so columns look even in monospace output. The last row has no padding; all rows share the same right edge.

Continue to Alphabet Pattern 28

Next up: symmetric decreasing alphabet squares (E…A…E layers).

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