Widening Alphabet Triangle (A, B B, C C, ...) in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Gap & Mirror

What You’ll Learn

Each row mirrors the same letter with a growing gap: row 0 prints centered A, row 1 prints B B, row 2 prints C C, until row 4 shows E E for five rows. Leading spaces (rows - 1 - r) center the triangle; the gap formula 2*r - 1 widens each row. Compare with Program 32 (centered palindrome pyramid) and Program 19 (mirrored halves). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Widening Rule

letter + gap + letter

Each row prints one letter, then for r > 0 a gap of 2*r - 1 spaces and the same letter again.

Leading Spaces

rows - 1 - r

line += " ".repeat(rows - 1 - r) centers each row under the single apex A.

Row Letter

String.fromCharCode(base + r)

ch = String.fromCharCode(base + r) picks the row letter - A on row 0, B on row 1, and so on.

Growing Gap

2*r - 1

line += " ".repeat(2 * r - 1) widens the gap between mirrored letters each row.

Live Preview

1–26 rows

Pick a row count and draw the widening alphabet triangle in the browser instantly.

O(n²)

Complexity

Row r prints 2*r - 1 gap spaces when r > 0; total output ≈ O(n²); extra memory stays O(1).

Introduction

A widening alphabet triangle prints each row as the same letter twice with a growing space gap, padded with leading spaces so the shape is centered. Row 0 prints a single A; each next row steps to the next letter - B B, C C, D D, and so on.

In JavaScript you solve it with an outer loop over row index r, leading spaces via " ".repeat(...), the row letter from charCodeAt(0)/String.fromCharCode(), and for r > 0 a widening gap before the mirrored letter - or build the whole row as one string for clarity.

Why it matters?

It combines three classic pattern skills - centering with spaces, conditional row logic, and a widening gap formula - the same building blocks used in hollow pyramids, diamonds, and symmetric ASCII art. Compare with Program 32 to see palindrome rows vs mirrored same-letter pairs.

Key Highlights

Leading Spaces

" " * (rows - 1 - r) - row 0 gets rows - 1 spaces; bottom row gets none.

First Letter

ch = String.fromCharCode(base + r) - prints the row letter once before the gap.

Mirror Letter

if r > 0: then gap spaces and the same ch again - skipped on row 0.

Row 0 Guard

if r > 0 ensures row 0 prints only one A, not A A.

In short: set base = "A".charCodeAt(0), loop r from 0 to rows - 1, append (rows - 1 - r) spaces, append ch, if r > 0 append (2*r - 1) gap spaces and ch again, then console.log(line) for the newline.

📝 Problem & Approach

Given a positive integer rows, print a centered triangle of rows lines. Row r prints (rows - 1 - r) leading spaces, then letter String.fromCharCode("A".charCodeAt(0) + r). For r > 0, print (2*r - 1) gap spaces and the same letter again.

JavaScript
// First 5 rows (widening triangle)
    A
   B B
  C   C
 D     D
E       E

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows (row letter runs A through the rows-th letter). Clamp to 1–26 for A–Z demos.
Printed outputtextWidening alphabet triangle: each row mirrors the same letter with a growing gap - bottom row has 2*rows - 1 spaces between the two letters plus leading spaces.

Minimal workflow

Pseudocode
base = "A".charCodeAt(0)
for r from 0 to rows-1:
    append (rows-1-r) leading spaces
    ch = String.fromCharCode(base + r)
    append ch
    if r > 0:
        append (2*r - 1) gap spaces
        append ch
    console.log(line)

Approach comparison

ApproachIdeaBest for
Direct print with gap guardLeading spaces, one letter, if r > 0 gap + mirror letterLearning conditional row logic and gap formula
One-line row builderpad + ch + ((gap + ch) if r > 0 else "") string expressionClearer debugging and row inspection
Program 32 contrastSee Program 32 (palindrome rows)Palindrome rows vs same-letter mirror pairs

⚡ Quick Reference

GoalPattern
Leading spacesline += " ".repeat(rows - 1 - r)
Outer loop (row index)for (let r = 0; r < rows; r++)
Row letterch = String.fromCharCode(base + r)
Gap spaces (r > 0)line += " ".repeat(2 * r - 1)
Mirror letter (r > 0)line += ch inside if (r > 0)
End the rowconsole.log(line)
Row builder variantpad + ch + ((" " * (2*r-1) + ch) if r > 0 else "")

📋 Leading Spaces vs Gap vs Mirror Letter

Three parts of every row - pick the mental model that clicks for you.

Leading spaces
rows - 1 - r
centers row

Top row gets the most padding; bottom row aligns flush left before letters.

Gap spaces (r > 0)
2*r - 1
1, 3, 5, 7...

Widens the space between mirrored letters - row 1 gets 1, row 4 gets 7.

Mirror letter (r > 0)
same ch
if r > 0

Prints the same letter again after the gap - guarded by if r > 0 so row 0 stays a single A.

Program 32 contrast
mirrored halves
different gap

Mirrored pattern with spaces between halves - see Program 19.

Context

When This Pattern Shows Up

Reach for widening alphabet triangles when teaching conditional row logic, gap formulas, and symmetric same-letter pairs after palindrome pyramids.

  1. After Program 32

    Program 32 prints palindrome rows (A, ABA, ABCBA). This pattern mirrors the same letter with a widening gap instead.

  2. Gap formula practice

    Master the 2*r - 1 gap formula before tackling full diamonds and hollow shapes.

  3. Centering with spaces

    The (rows - 1 - r) space formula appears in centered stars, numbers, and diamond patterns.

  4. Gateway to Program 34

    Next pattern closes into a full alphabet diamond - another symmetric shape variation.

  5. Not a UI layout tool

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

Key benefit: one program that combines centering spaces with a widening gap formula - the same two skills used in diamond patterns, hollow pyramids, and symmetric ASCII art far beyond alphabet demos.

🔮 Live Preview

Choose a row count between 1 and 26 and draw the widening alphabet triangle in the browser.

Try 5 (A through E E) or 3 (A, B B, C C). Up to 26 rows use A–Z.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed five rows with leading spaces and a widening gap, prompt input, and a one-line row-builder variant for clarity. Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print five rows of the widening alphabet triangle with leading spaces and a mirrored letter gap.

Example 1 — Fixed rows = 5

Hard-coded height - ideal for first demos and screenshots.

JavaScript
let rows = 5;
rows = Math.max(1, Math.min(rows, 26));

const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {
  let line = "";
  line += " ".repeat(rows - 1 - r);
  const ch = String.fromCharCode(base + r);
  line += ch;
  if (r > 0) {
    line += " ".repeat(2 * r - 1);
    line += ch;
  }
  console.log(line);
}
Try it Yourself

How It Works

The outer loop walks row index r from 0 to 4. For each row, line += " ".repeat(rows - 1 - r) centers the row, then ch = String.fromCharCode(base + r) picks the row letter. For r > 0, line += " ".repeat(2 * r - 1) widens the gap before the mirrored letter. Row 0 prints only A with four leading spaces; row 4 prints E E with a 7-space gap and no leading spaces.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows and clamp to 1–26. Validate parseInt(prompt(), 10) with Number.isFinite in real apps.

JavaScript
let rows = parseInt(prompt("Enter number of rows (max 26):"), 10);
if (!Number.isFinite(rows)) {
  console.log("Please enter a whole number.");
} else {
  rows = Math.max(1, Math.min(rows, 26));

  const base = "A".charCodeAt(0);

  for (let r = 0; r < rows; r++) {
    let line = "";
    line += " ".repeat(rows - 1 - r);
    const ch = String.fromCharCode(base + r);
    line += ch;
    if (r > 0) {
      line += " ".repeat(2 * r - 1);
      line += ch;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same widening triangle core as Example 1; only the row count comes from prompt. Three rows produce A, B B, and C C with 2, 1, and 0 leading spaces respectively.

⚡ One-Line Row Builder

Build each row as a single string expression with pad, letter, and optional gap.

Example 3 — One-Line Row Builder Variant

Combine pad, letter, and conditional gap in one row string - same logic, easier row inspection.

JavaScript
let rows = 5;
rows = Math.max(1, Math.min(rows, 26));

const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {
  const pad = " ".repeat(rows - 1 - r);
  const ch = String.fromCharCode(base + r);
  const row = pad + ch + (r > 0 ? " ".repeat(2 * r - 1) + ch : "");
  console.log(row);
}
Try it Yourself

How It Works

pad holds the leading spaces and ch is the row letter. The ternary adds the gap and second letter only when r > 0 - identical output to Examples 1 and 2, with the full row visible as one string for debugging.

🧠 How the Algorithm Prints Rows

1

Set up bounds

Clamp rows, then set base = "A".charCodeAt(0) for the alphabet starting point.

base / rows
2

Print leading spaces

line += " ".repeat(rows - 1 - r) centers row r before any letters.

Center
3

Gap and mirror

Append ch = String.fromCharCode(base + r), then if r > 0 append " ".repeat(2 * r - 1) and ch again.

Mirror
4

New line

console.log(line) ends the row after leading spaces, letter, optional gap, and mirror finish; the outer loop advances r.

Break
=

Pattern complete

Total characters grow with gap spaces: row r prints O(r) gap spaces — O(n²) time, O(1) extra memory (loop version).

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of r and see how leading spaces, row letter, gap, and mirror letter produce each widening row.

rletterlead spacesgapmirrorfull row
0A4(none)(none)A
1B31BB B
2C23CC C
3D15DD D
4E07EE E

Highlight rows: r = 0 (4 lead spaces, A only), r = 1 (3 spaces, B + 1 gap + B → B B), r = 4 (0 spaces, E + 7 gap + E). Gap grows by 2 each row: 2*r - 1 gives 1, 3, 5, 7 for rows 1–4.

Use Cases

Where widening alphabet triangles show up beyond the homework prompt.

1. After Program 32

Program 32 prints palindrome rows (A, ABA, ABCBA). This pattern mirrors the same letter with a widening gap instead.

Example: compare palindrome ABCBA rows vs B B / C C mirror pairs side by side.

2. Gap formula practice

Reinforce the 2*r - 1 gap formula before tackling hollow pyramids and full diamonds.

Example: trace row 2 (r=2) on paper: lead spaces=2, letter=C, gap=3, mirror=C.

3. Program 32 contrast

Mirrored halves with spaces between - see Program 19.

Example: compare Program 19’s mirrored halves with this same-letter widening gap approach.

4. Full diamond extension

Mirror the triangle downward to close a full alphabet diamond.

Example: after the top half, loop r from rows-2 down to 0 with the same gap + mirror row logic.

5. Complexity intuition

Sum of widening gap spaces makes O(n²) concrete for beginners.

Example: 5 rows → gap spaces 0+1+3+5+7 = 16 plus 9 letters.

6. Interview warm-up

Classic nested-loop question that tests gap formula and centering spaces.

Example: explain why row 0 skips the gap and mirror without running code.

Pro Tip: say “leading spaces, letter, if r>0 gap then same letter” before coding - that story prevents double A on row 0 and wrong gap width.

Advantages

Why this pattern earns a spot after the centered palindrome pyramid from Program 32.

  1. 1. Teaches Gap & Mirror

    if r > 0 gap guard - a pattern reused whenever row 0 is special.

  2. 2. Centered Symmetry

    Leading spaces create a visually balanced pyramid - every row aligns under the apex.

  3. 3. Two Implementations

    Direct print loops for learning; one-line row builder for clearer debugging.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters (row builder uses O(r) per row string).

Pro Tip: when row 0 prints only A, the mirror loop range is empty - that is correct, not a bug.

Usage Tips

Small habits that keep widening alphabet triangle code clean.

  1. 1. Name letter explicitly

    Use ch = String.fromCharCode(base + r) - keeps gap and mirror loops readable.

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

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

  3. 3. Clamp rows early

    rows = Math.max(1, Math.min(rows, 26)) keeps demos inside A–Z.

  4. 4. Guard row 0 separately

    if r > 0: must wrap gap and mirror - never print a second A on row 0.

  5. 5. Dry-run rows = 3

    Trace A, B B, C C with 2, 1, 0 leading spaces on paper before coding larger demos.

Pro Tip: if gaps look too narrow, check the formula - it should be 2*r - 1, not 2*r.

Common Pitfalls

Mistakes that commonly break widening alphabet triangles.

  1. 1. Printing second letter on r=0

    Forgetting if r > 0 prints A A on row 0 - two letters at the apex.

    → Wrap gap and mirror in if r > 0: so row 0 prints only one A.

  2. 2. Wrong gap formula

    Using 2*r instead of 2*r - 1 makes gaps one space too wide starting at row 1.

    → Use 2*r - 1 for the gap - row 1 needs 1 space, row 4 needs 7.

  3. 3. Wrong leading spaces

    Using r lead spaces or rows - r misaligns the triangle - rows lean or over-indent.

    → Use rows - 1 - r leading spaces so row 0 gets the most padding.

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

    Non-numeric input yields NaN with bare parseInt(prompt(), 10).

    → Validate with Number.isFinite and clamp the range.

  5. 5. Forgetting the row 0 guard

    Printing gap + mirror on every row including r=0 produces A A instead of a single centered A.

    → Keep gap and mirror inside if r > 0: on every row.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single letter

Output is just A with no leading spaces when rows=1 - gap block skipped because r=0.

rows = 0

Empty pattern

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

rows = 26

Full alphabet

26 rows with letter Z - bottom row prints ...Z...Z... with no leading spaces.

rows > 26

Past Z

Clamp to 26 or define a wrap/error policy before printing.

Bad input

Non-numeric input

Use Number.isFinite before clamping rows.

Case

Lowercase variant

Same loops work with base = "a".charCodeAt(0) and lowercase output.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 32

  • Program 32: palindrome rows (A, ABA, ABCBA)
  • This pattern: same rows with leading spaces to center
  • See Program 32

2. Implement row builder variant

  • Rewrite Example 1 using the one-line row builder from Example 3
  • Verify identical output for rows=5

3. Compare with Program 19

  • Program 19: mirrored halves with spaces between
  • This pattern: same letter twice with widening internal gap
  • See Program 19

4. Continue to Program 34

  • Next pattern - alphabet diamond
  • Builds on symmetric shape ideas
  • See Program 34

Notes

  • Gap count. Row r prints 2r - 1 gap spaces when r > 0. Over n rows the total gap spaces sum to (n-1)².
  • Row 0 guard: if r > 0: - without it row 0 would print A A instead of a single apex.
  • One-line row builder is equivalent to the direct-print version - use whichever fits your lesson.
  • Clamp to 26 rows for A–Z demos; compare with Program 32 for palindrome rows vs same-letter mirrors.

Quick Takeaway: outer loop sets r, print (rows - 1 - r) spaces, print ch, if r > 0 print gap and ch again, then break the line - that is the whole widening alphabet triangle.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Direct print with gap guard (Examples 1–2)O(rows²)O(1)
Row builder variant (Example 3)O(rows²)O(r) for row string per row
Wrap Up

🎉 Conclusion

The widening alphabet triangle combines centering spaces with a growing gap and mirrored same-letter rows. Master the direct-print version, then try the one-line row builder for clearer debugging.

Practice the three examples above, then continue to Program 34 in the alphabet pattern series.

Print leading spaces, guard row 0 with if r > 0, use gap formula 2*r - 1, clamp rows to 26, and compare with Program 32 (centered palindrome pyramid).

💡 Best Practices

✅ Do

  • Set base = "A".charCodeAt(0), clamp rows to 1–26
  • Append (rows - 1 - r) leading spaces each row
  • Print ch, then if r > 0: gap 2*r-1 and mirror ch
  • Use line += ch for letters; console.log(line) after each row
  • Compare output with Program 32 to see palindrome vs mirror pairs
  • Try the one-line row builder for debugging

❌ Don’t

  • Print gap + mirror on r=0 - produces A A at apex
  • Hardcode ASCII 65 instead of "A".charCodeAt(0)
  • Use 2*r for gap - gaps one space too wide
  • Use wrong leading space count - triangle will lean left or right
  • Forget if r > 0 - row 0 prints two letters
  • Let rows exceed 26 without a defined policy

Key Takeaways

Knowledge Unlocked

Five things to remember about this widening alphabet triangle

Print the widening triangle the beginner-friendly way.

5
Core concepts
  02

Leading spaces

rows - 1 - r

Center
↑A 03

Gap formula

2*r - 1

Code
↓A 04

Row 0 guard

if r > 0

Code
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Each row prints the same letter twice with a growing gap between them, except row 0 which prints a single centered A. Row r uses (rows-1-r) leading spaces, letter String.fromCharCode('A'.charCodeAt(0)+r), then for r>0 a gap of 2*r-1 spaces and the same letter again.
Row 0 is the apex - only one A should appear at the top. The if (r > 0) guard prevents appending a gap and duplicate letter on the first row.
Append (rows - 1 - r) leading spaces before the first letter. Row 0 gets the most spaces; the bottom row gets zero.
For r > 0, append (2*r - 1) spaces between the two copies of the row letter. Row 1 gets 1 gap space (B B), row 2 gets 3 (C C), row 4 gets 7 (E E).
Program 32 prints palindrome rows (A, ABA, ABCBA) with ascending and descending letter loops. Program 33 prints the same letter twice per row with a widening space gap - not a full palindrome string.
Each row letter is String.fromCharCode('A'.charCodeAt(0) + r). With rows > 26 you would need characters beyond Z unless you define a wrap or error policy.
O(n^2) where n is rows. Row r prints O(r) gap spaces plus O(n) leading spaces; the sum over all rows is O(n^2).
Use parseInt(prompt(), 10) and check Number.isFinite, then clamp rows between 1 and 26.

Did you Know? 🔊

Row r prints (rows - 1 - r) leading spaces, then letter String.fromCharCode('A'.charCodeAt(0) + r). For r > 0, a gap of 2*r - 1 spaces separates a second copy of the same letter. Row 0 is a single centered A.

Continue to Program 34

Next up: the alphabet diamond - extend this widening triangle into a full symmetric shape.

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