Right-Aligned Sequential Pyramid in JavaScript

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

What You’ll Learn

Print letters in a running sequence (A, then B C, then D E F…) while keeping the triangle right-aligned by printing empty 2-column cells first. View output in a monospace terminal because alignment relies on fixed-width cells. Compare Program 13 (sequential, left-aligned) and Program 20 (right-aligned reverse). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Right-aligned sequence

Growing rows of continuous letters sit on the right.

Running k

Never reset

k += 1 only when a letter prints — A…O across 5 rows.

Fixed Cells

Width 2

Pad with " "; append letters with String.fromCharCode(k).padStart(2, " ").

Pad Rule

j > i

Empty cells first, then letters for right alignment.

Live Preview

1–6 rows

Pick a height (max 6 keeps letters within A–U).

O(n²)

Complexity

n rows × n cells per fixed-width scan.

Introduction

A right-aligned sequential alphabet pyramid prints a continuous stream of letters into a right-aligned triangle, using fixed-width cells so empty pads and letters share the same column size.

In JavaScript you solve it with nested loops, a running counter (charCodeAt/fromCharCode), and matching pad/letter widths (" " vs ch.padStart(2, " ")).

Why it matters?

It combines continuous counters, right alignment, and format-width printing — three skills that show up often in console layout labs.

Key Highlights

Running Counter

k never resets between rows.

Right Align

Empty cells print before letters.

Width 2

" " matches ch.padStart(2, " ").

Monospace

Alignment needs a fixed-width font.

In short: for each row i, scan n cells - append " " while j > i, otherwise append the next letter with padStart(2, " "), then call console.log(line).

📝 Problem & Approach

Given a row count n (or fixed 5), print a right-aligned pyramid of continuous alphabet letters in 2-column cells.

JavaScript
// Five rows (monospace; each cell is width 2)
//         A
//       B C
//     D E F
//   G H I J
// K L M N O

Inputs & Outputs

ItemTypeDescription
nintNumber of rows. Letter count = n(n+1)/2 (15 for n=5).
Printed outputtextRight-aligned continuous letters in fixed-width cells.

Minimal workflow

Pseudocode
k = "A".charCodeAt(0)
for i in 1..n:
    line = ""
    for j from n down to 1:
        if j > i: line += "  "
        else: line += String.fromCharCode(k++).padStart(2, " ")
    console.log(line)

Approach comparison

ApproachIdeaBest for
Fixed-width scanPad or letter in each of n cellsMatching this classic sample
Explicit pad + lettersPrint pads, then i letters via k++Clearer reading / teaching rewrite

⚡ Quick Reference

GoalPattern
Counterk = "A".charCodeAt(0) (outside outer loop)
Rowsfor (let i = 1; i <= n; i++)
Scan cellsfor (let j = n; j >= 1; j--)
Pad cellline += " " when j > i
Letter cellline += String.fromCharCode(k++).padStart(2, " ")
Left-aligned sequenceSee Program 13

📋 Pad vs Letter vs console.log

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

line += " "
pad

2-column empty cell for right alignment

line += padStart; k++
letter

Next sequential letter in a width-2 field

k outside
stream

Continues A, B, C… across every row

console.log
break

Ends the row after n cells

Context

When This Pattern Shows Up

Reach for this when teaching continuous counters with fixed-width alignment.

  1. After Program 13

    Keep the running counter; add right alignment with width-2 cells.

  2. String-format drills

    Practice ch.padStart(2, " ") matching pad width exactly.

  3. Compare with Program 20

    Same right-align idea; sequential fill vs reverse suffixes.

  4. Monospace layout labs

    Show why proportional fonts break column alignment.

  5. Not a UI layout tool

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

Key benefit: matching pad and letter widths turns a continuous alphabet stream into a clean right-aligned pyramid.

🔮 Live Preview

Choose between 1 and 6 rows and draw the right-aligned sequential pyramid in the browser (monospace cells).

Try 5 (through O) or 3 (through F). Max 6 keeps letter count within A–U.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed 5 rows, user-chosen row count, and an explicit pad-then-letters 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 sequential rows with a running counter.

Example 1 — Fixed 5 Rows

A single counter k increments only when a letter is appended, and padStart(2, " ") keeps columns aligned.

JavaScript
let k = "A".charCodeAt(0);

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

How It Works

When i = 3, two cells append " " and three cells append D, E, F via k++. Because k is outside the outer loop, the next row continues at G.

📈 Practical Variant

Let the user choose how many rows to print.

Example 2 — Row Count Input

Note: for large values, letters will go past Z. Validate parseInt(prompt()) with Number.isFinite and a letter-budget cap in real apps.

JavaScript
let n = parseInt(prompt("Enter number of rows (like 5):"), 10);
if (!Number.isFinite(n)) {
  console.log("Please enter a whole number.");
} else {
  n = Math.max(1, Math.min(n, 6));
  let k = "A".charCodeAt(0);

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

How It Works

Same pad/letter rules; only the shared width follows n. Letter count is n(n+1)/2 - cap so it stays ≤ 26 for A–Z only.

⚡ Explicit Style

Same shape with separate pad and letter loops.

Example 3 — Pad Cells, Then Letters

Often clearer to read: append n - i empty cells, then i sequential letters.

JavaScript
const n = 5;
let k = "A".charCodeAt(0);

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

How It Works

Row i needs n - i pad cells and i letters from the continuous counter. Same visual pyramid as the single-scan version - only the loop structure changes.

🧠 How the Algorithm Prints Rows

1

k = "A".charCodeAt(0)

A single running counter that never resets between rows.

Counter
2

Right alignment via empty cells

The inner scan runs from n down to 1. When j > i we append two spaces to keep the same cell width as a letter.

Align
3

Fixed-width letter printing

We print letters using ch.padStart(2, " "), so each letter occupies 2 columns and lines up with the padding.

Columns
4

New line

console.log(line) ends the row so the next row continues the same k.

Break
=

Sequence continues

Because k increments only when we print a letter, the alphabet continues across rows — O(n²) time.

🔎 Worked Walkthrough — 5 rows

Trace each row’s pads, letters, and the running counter range.

iPad cellsLettersPrinted row
14A········A
23B C······B C
32D E F····D E F
41G H I J··G H I J
50K L M N OK L M N O

Total letters: 1+2+3+4+5 = 15 (A through O). Each cell is 2 columns wide.

Use Cases

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

1. Continuous Fill Labs

Clearest demo of a counter that never resets across rows.

Example: reset k once and compare to Program 1-style prefixes.

2. Pair with Program 13

Same sequence — left-aligned vs right-aligned layout.

Example: print both for n = 5 side by side.

3. Format Width Practice

Match pad string length to ch.padStart(2, " ") field width.

Example: try one-space pads and watch columns break.

4. Explicit Pad Rewrite

Teach pad count separately from letter count (Example 3).

Example: compare scan vs pad+letters outputs.

5. Complexity Intuition

Triangular letter counts make O(n²) easy to see.

Example: 5 rows print 15 letters (plus pad cells).

6. Alphabet Budget

Practice capping n so n(n+1)/2 stays ≤ 26.

Example: n=7 needs 28 letters — past Z.

Pro Tip: say “empty cells first, then keep counting letters” before coding — that story prevents resetting k or mismatched widths.

Advantages

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

  1. 1. Instant Visual Feedback

    Mismatched pad width or a reset counter shows up immediately.

  2. 2. Two Clear Rewrites

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

  3. 3. Format Practice

    A natural place to learn JavaScript string formatting with ch.padStart(2, " ").

  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/letter rewrite as a clarity upgrade afterward.

Usage Tips

Small habits that keep right-aligned sequential pyramids clean.

  1. 1. Keep k Outside

    Do not reset the counter each row if you want continuous letters.

  2. 2. Match Pad Width to Letters

    Use two spaces when letters use ch.padStart(2, " ").

  3. 3. Use Number.isFinite

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

  4. 4. Cap the Letter Budget

    Keep n(n+1)/2 ≤ 26 for A–Z-only output.

  5. 5. Use a Monospace Font

    Proportional fonts make width-2 cells look misaligned.

Pro Tip: if every row starts with A, you almost certainly reset k inside the outer loop.

Common Pitfalls

Mistakes that commonly break right-aligned sequential pyramids.

  1. 1. Resetting the Counter

    Each row starts at A again — that is a different pattern.

    → Keep k outside the outer loop.

  2. 2. One-Space Padding

    Empty cells become narrower than ch.padStart(2, " ") letter fields.

    → Append " " (two spaces) for each pad cell.

  3. 3. Proportional Font Preview

    Columns look broken even when the code is correct.

    → View output in a monospace terminal/font.

  4. 4. Blind parseInt(prompt())

    Letters or empty input throw FormatException.

    → Validate parseInt(prompt()) with Number.isFinite and re-prompt on failure.

  5. 5. Walking Past Z

    Large n needs more than 26 letters.

    → Cap n so n(n+1)/2 ≤ 26, or define wrap/stop policy.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single letter

Output is just A (no pads).

n = 5

Classic sample

15 letters through O.

n = 3

Smaller pyramid

Through F (Example 2).

n = 7

Past Z

Needs 28 letters — decide wrap/stop policy.

Bad input

Non-numeric prompt()

parseInt(prompt()) yields NaN — use Number.isFinite.

Case

Lowercase

Same loops with k = "a".charCodeAt(0).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Drop the alignment

  • Print sequential letters left-aligned
  • Compare with Program 13

2. Reset vs continuous

  • Reset k = "A".charCodeAt(0) each row once
  • See how the meaning changes

3. Explicit pad version

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

4. Continue to Program 23

  • Right-aligned reverse letter pyramid
  • See Program 23

Notes

  • Continuous k. Increment only when printing a letter; never reset between rows for this pattern.
  • Pad width must match letter field width (" "ch.padStart(2, " ")).
  • Letter count for n rows is the triangular number n(n+1)/2.
  • Monospace fonts are required for columns to look correct.

Quick Takeaway: pad empty width-2 cells first, print the next letters with matching width, keep counting across rows, then break the line.

⏱️ Time and Space Complexity

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

Each of n rows scans n cells (or pads + letters totaling n), so total work is O(n²).

Wrap Up

🎉 Conclusion

The right-aligned sequential alphabet pyramid is a small nested-loop exercise with lasting payoff: a continuous letter counter, fixed-width cells, and leading empty cells for alignment. Master the classic A…O sample, then try user input and the explicit pad rewrite.

Practice the three examples above, then continue to Program 23’s right-aligned reverse alphabet pyramid.

Keep k outside, match pad and letter widths, print empty cells while j > i, then advance letters and break the line.

💡 Best Practices

✅ Do

  • Keep the letter counter outside the outer loop
  • Match pad width to letter field width
  • View output in a monospace font
  • Validate parseInt(prompt()) with Number.isFinite and cap the letter budget
  • State O(n²) when asked about complexity

❌ Don’t

  • Reset k each row for this pattern
  • Pad with a single space when letters use width 2
  • Assume proportional fonts will align columns
  • Ignore overflow past Z on large n
  • Call console.log(line) inside the cell loop

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

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

5
Core concepts
k 02

Counter

Never reset

Code
2 03

Width

" " & {0,2}

Code
04

console.log

Ends each scan

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Because the counter is not reset inside the outer loop. Each time a letter is printed we increment it so the sequence continues A, then B C, then D E F, and so on.
Letters are formatted with width 2 using ch.padStart(2, ' '). Two spaces keep empty cells the same width so columns align.
Decide a rule: stop at Z, wrap back to A, or switch to a longer alphabet list. Then apply it when incrementing the counter.
line += ' ' or line += ch.padStart(2, ' ') stays on the same conceptual row for each cell. console.log(line) ends the row after the fixed-width scan finishes.
Program 13 also uses a running letter counter, but prints left-aligned without fixed-width padding. This pattern right-aligns by printing empty 2-column cells first.
O(n^2) for n rows when each row scans n slots in the inner loop.
Use parseInt with Number.isFinite after prompt(), require n >= 1, and cap so n(n+1)/2 <= 26 if you want only A-Z letters.
Yes. Append n - i empty width-2 cells, then i letters via the counter. Example 3 on this page shows that style.

Did you Know? 🔊

Each slot is 2 columns wide. Padding uses " " and letters use ch.padStart(2, " ") so columns line up in monospace output. The counter never resets, so letters run continuously from A to O for 5 rows.

Continue to Alphabet Pattern 23

Next up: right-aligned reverse alphabet pyramids (E, E D, E D C, …).

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