Alphabet X Pattern (Diagonal Letters A..E) in JavaScript

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

What You’ll Learn

Each row places one letter on two diagonals forming an X shape: row 0 prints A at both ends, each next row steps inward with B, C, D, until a single E lands in the center for five rows. A column loop with left = r and right = width - 1 - r teaches 2D grid thinking. Compare with star X pattern (0 and *). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

X Rule

Two diagonals

Each row prints one letter at left and right columns; all other columns are spaces.

Left Diagonal

col = r

left = r moves one column right each row - top-left to center.

Right Diagonal

col = width - 1 - r

right = width - 1 - r moves one column left each row - top-right to center.

Grid Width

2*rows - 1

width = 2 * rows - 1 gives equal space on both sides of the center column.

Live Preview

1–26 rows

Pick a row count and draw the alphabet X pattern in the browser instantly.

O(n²)

Complexity

n rows × 2n - 1 columns per row ≈ O(n²); extra memory stays O(1).

Introduction

An alphabet X pattern places letters on two diagonals inside a grid of width 2*rows - 1. Row 0 prints A at both ends; each row steps inward until the diagonals meet at one center letter.

In JavaScript you solve it with an outer loop over row index r, an inner column loop, and charCodeAt(0)/String.fromCharCode() - or build each row in an array and console.log(row.join("")) for clarity.

Why it matters?

It teaches 2D grid coordinates - mapping row and column indices to print positions - the same skill used in matrices, game boards, and ASCII art. When left == right, both diagonals meet and only one character prints.

Key Highlights

Grid Width

width = 2 * rows - 1 - for rows=5 the grid is 9 columns wide.

Left Diagonal

left = r - column index grows one step right each row.

Right Diagonal

right = width - 1 - r - column index shrinks one step left each row.

Center Meet

When left == right, only one letter prints - not two copies.

In short: set width = 2 * rows - 1 and base = "A".charCodeAt(0), loop r from 0 to rows - 1, compute left = r and right = width - 1 - r, append the row letter at those columns and spaces elsewhere, then console.log(line) for the newline.

📝 Problem & Approach

Given a positive integer rows, print an X-shaped grid of rows lines, each 2*rows - 1 characters wide. Row r prints String.fromCharCode("A".charCodeAt(0) + r) at columns left = r and right = width - 1 - r; all other positions are spaces.

JavaScript
// First 5 rows (width = 9)
// A       A
//  B     B
//   C   C
//    D D
//     E

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows (also the row letter runs A through the rows-th letter). Clamp to 1–26 for A–Z demos.
Printed outputtextX-shaped grid: letters on two diagonals, spaces elsewhere - width 2*rows - 1 per line.

Minimal workflow

Pseudocode
width = 2 * rows - 1
base = "A".charCodeAt(0)
for r from 0 to rows-1:
    ch = String.fromCharCode(base + r)
    left = r
    right = width - 1 - r
    for c from 0 to width-1:
        append ch if c==left or c==right else space
    console.log(line)

Approach comparison

ApproachIdeaBest for
Column loopfor (let c = 0; c < width; c++) append letter or spaceLearning 2D grid coordinates and diagonals
Join arrayBuild row in an array, console.log(row.join(""))Clearer debugging and row inspection
Star X contrastSee Program 45 (0 and * X)Same diagonal logic with symbols instead of letters

⚡ Quick Reference

GoalPattern
Grid widthwidth = 2 * rows - 1
Outer loop (row index)for (let r = 0; r < rows; r++)
Row letterch = String.fromCharCode(base + r)
Diagonal columnsleft = r; right = width - 1 - r
Column loopfor (let c = 0; c < width; c++) line += (c === left || c === right) ? ch : " "
End the rowconsole.log(line)
Array join variantrow.push(c === left || c === right ? ch : " "); console.log(row.join(""))

📋 Left Diagonal vs Right Diagonal vs Join Row

Three ways to think about the same X grid - pick based on what you are learning.

Left diagonal
left = r
col moves right

Top-left to center - column index equals row index.

Right diagonal
right = width-1-r
col moves left

Top-right to center - column index shrinks as rows grow.

Join row
row.push(...)
row.join("")

Collect characters in an array, then log one string - easier to inspect each row while debugging.

Star X contrast
* on diagonals
0 elsewhere

Same diagonal positions - see Program 45 with 0 and *.

Context

When This Pattern Shows Up

Reach for diagonal column loops when you need letters (or symbols) on two crossing lines inside a fixed-width grid.

  1. After Program 30

    Program 30 mixes prefix and suffix on one line. This pattern uses a 2D grid with diagonal columns.

  2. 2D coordinates

    Practice mapping (r, c) pairs to print positions before tackling matrices.

  3. Diagonal grids

    Same left/right column rule appears in star X patterns and hollow diamond shapes.

  4. Gateway to Program 32

    Next pattern builds a centered palindrome pyramid - another symmetric shape.

  5. Not a UI layout tool

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

Key benefit: one program that proves you can map row/column indices to diagonal positions - a pattern used in matrices, game boards, and ASCII art far beyond alphabet demos.

🔮 Live Preview

Choose a row count between 1 and 26 and draw the alphabet X pattern in the browser.

Try 5 (A..E diagonals) or 3 (A at corners, B, center C). Up to 26 rows use A–Z.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed five rows with diagonal column loops, prompt input with ternary form, and an array-join 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 alphabet X pattern with left/right diagonal column loops.

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 width = 2 * rows - 1;
const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {  // 0..rows-1
  const ch = String.fromCharCode(base + r);
  const left = r;
  const right = width - 1 - r;
  let line = "";

  for (let c = 0; c < width; c++) {
    if (c === left || c === right) {
      line += ch;
    } else {
      line += " ";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

The outer loop walks row index r from 0 to 4. For each row, ch = String.fromCharCode(base + r) selects the letter and left = r, right = width - 1 - r mark the two diagonal columns. The inner loop scans every column: append the letter when c === left or c === right, otherwise append a space. On the last row left === right === 4, so only one E appears in the center.

📈 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 width = 2 * rows - 1;
  const base = "A".charCodeAt(0);
  for (let r = 0; r < rows; r++) {
    const ch = String.fromCharCode(base + r);
    const left = r;
    const right = width - 1 - r;
    let line = "";
    for (let c = 0; c < width; c++) {
      line += (c === left || c === right) ? ch : " ";
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same diagonal grid core as Example 1; only the row count comes from prompt. Three rows use width 5 with letters A–C on the diagonals - row 2 prints B at columns 1 and 3.

⚡ Array Join Variant

Build each row in an array, then log with row.join("").

Example 3 — row.join("") Variant

Collect characters in an array for clearer row inspection - same logic, easier debugging.

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

const width = 2 * rows - 1;
const base = "A".charCodeAt(0);

for (let r = 0; r < rows; r++) {
  const ch = String.fromCharCode(base + r);
  const left = r;
  const right = width - 1 - r;
  const row = [];

  for (let c = 0; c < width; c++) {
    row.push((c === left || c === right) ? ch : " ");
  }

  console.log(row.join(""));
}
Try it Yourself

How It Works

The column loop pushes each character to row instead of appending to a string immediately. row.join("") builds the full line - identical output to Examples 1 and 2, but you can inspect row before logging during debugging.

🧠 How the Algorithm Prints Rows

1

Set up bounds

Clamp rows, then set width = 2 * rows - 1 and base = "A".charCodeAt(0) for the grid and alphabet.

width / base
2

Outer loop (row index)

for (let r = 0; r < rows; r++) walks each row from 0 to rows - 1, computing left, right, and ch.

r = 0..n-1
3

Column loop

for (let c = 0; c < width; c++) appends the letter at diagonal columns and spaces elsewhere with line += ....

Inner loop
4

New line

console.log(line) ends the row after the column loop finishes; the outer loop advances r to the next row.

Break
=

Pattern complete

Total characters: n × (2n - 1) ≈ O(n²)O(n²) time, O(1) extra memory (loop version).

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of r and see how left, right, and the row letter produce each printed line.

rLetterleftrightRow output
0A08A A
1B17B B
2C26C C
3D35D D
4E44E (left==right)

Total character prints: 5 × 9 = 45 = rows × width for rows = 5.

Use Cases

Where diagonal grid patterns show up beyond the homework prompt.

1. After Program 30

Program 30 mixes prefix and suffix on one line. This pattern uses a 2D grid with diagonal columns.

Example: compare fixed-width rows vs spaced X grid side by side.

2. 2D coordinate practice

Reinforce mapping (r, c) pairs to print positions before tackling matrices.

Example: trace left and right for row 2 (r=1) on paper before coding.

3. Star X patterns

Same diagonal positions with * instead of letters - see Program 45.

Example: swap ch for * and keep the column loop.

4. Number X grid

Swap letters for digits 1..n at the same diagonal columns.

Example: rows=3 prints 1 at corners and 3 in the center.

5. Complexity intuition

Rectangular totals make O(n²) concrete for beginners.

Example: 5 rows → 45 characters printed (5 × 9).

6. Interview warm-up

Classic nested-loop question that tests diagonal column indices and center merge.

Example: explain why only one E prints when rows=5 without running code.

Pro Tip: say “letter at left and right columns, space everywhere else” before coding - that story prevents wrong width or missing spaces.

Advantages

Why this pattern earns a spot after the mixed alphabet rows from Program 30.

  1. 1. Teaches 2D Grids

    Row and column loops map directly to matrix coordinates - a core programming skill.

  2. 2. Symmetric Shape

    The X is visually symmetric - left and right diagonals mirror each other.

  3. 3. Two Implementations

    Line-build version for learning; array-join version for clearer debugging.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters (join variant uses O(width) per row).

Pro Tip: when left == right on the last row, the or condition still prints exactly once per column - no special case needed.

Usage Tips

Small habits that keep alphabet X pattern code clean.

  1. 1. Name left and right

    Use left = r and right = width - 1 - r - keep r and c for loop variables.

  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. Compute width once

    width = 2 * rows - 1 before the row loop - do not recompute inside unless rows changes.

  5. 5. Dry-run rows = 3

    Trace A at corners, B, center C on paper before coding larger demos.

Pro Tip: if the shape looks like a solid block, you likely forgot spaces - only diagonal columns should print letters.

Common Pitfalls

Mistakes that commonly break alphabet X patterns.

  1. 1. Wrong width formula

    Using width = rows or width = 2 * rows misaligns the diagonals - the X looks skewed or truncated.

    → Use width = 2 * rows - 1 so the top row has equal space on both sides.

  2. 2. Printing letter twice at center

    Some beginners add a separate branch when left == right and accidentally print the letter twice.

    → The condition c == left or c == right already prints once per column - no extra branch needed.

  3. 3. Hardcoded ASCII 65

    Magic numbers like String.fromCharCode(65 + r) work but break readability and lowercase variants.

    → Use base = "A".charCodeAt(0) and String.fromCharCode(base + r) instead of raw ASCII values.

  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. Missing spaces between letters

    Printing only letters without spaces collapses the X into a solid diagonal block.

    → The inner loop must append a space character for every non-diagonal column.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single letter

Output is just A on one line - left == right == 0, so one letter at column 0.

rows = 0

Empty pattern

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

rows = 26

Full alphabet

26 rows with width 51 - last row prints Z once at the center column.

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 30

  • Program 30: mixed rows ABCDE, BABCD, CBABC
  • This pattern: diagonal X with spaced grid
  • See Program 30

2. Implement join-row form

  • Rewrite Example 1 using row.push and row.join("")
  • Verify identical output for rows=5

3. Star X with 0 and *

4. Continue to Program 32

  • Next pattern - centered alphabet palindrome pyramid
  • Builds on symmetric shape ideas
  • See Program 32

Notes

  • Grid count. Total characters for n rows is n × (2n - 1) - each row scans the full width.
  • Column loop: for (let c = 0; c < width; c++) with left = r and right = width - 1 - r.
  • row.join("") after building in an array is equivalent to the line-build version - use whichever fits your lesson.
  • Clamp to 26 rows for A–Z demos; row 26 prints Z once at the center when diagonals meet.

Quick Takeaway: outer loop sets r, compute left and right, print the row letter at diagonal columns and spaces elsewhere, then break the line - that is the whole alphabet X pattern.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Column loop (Examples 1–2)O(rows²)O(1)
Join variant (Example 3)O(rows²)O(width) for the row list per line
Wrap Up

🎉 Conclusion

The alphabet X pattern teaches 2D grid thinking - mapping row and column indices to diagonal print positions. Master the line-build version, then try the array-join variant for clearer debugging.

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

Set width, left, and right each row, run the column loop, clamp rows to 26, and compare with star X pattern (Program 45) using the same diagonal logic.

💡 Best Practices

✅ Do

  • Set base = "A".charCodeAt(0), width = 2 * rows - 1
  • Compute left = r and right = width - 1 - r each row
  • Run the column loop on every row
  • Append a space for non-diagonal columns - not just skip characters
  • Use line += ch or a ternary in the column loop; console.log(line) after
  • Clamp rows to 1–26 for A–Z demos

❌ Don’t

  • Use wrong width formula - diagonals will not align
  • Hardcode ASCII 65 instead of "A".charCodeAt(0)
  • Skip spaces - the X collapses into solid diagonals
  • Add a duplicate print when left == right - one column already prints once
  • Call console.log inside the column loop
  • Let rows exceed 26 without a defined policy

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet X pattern

Print the X grid the beginner-friendly way.

5
Core concepts
↓A 02

Left diagonal

left = r

Code
B→ 03

Right diagonal

width - 1 - r

Code
[] 04

Join array

row.join("")

Alt
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Letters sit on two diagonals forming an X shape. Row r prints String.fromCharCode('A'.charCodeAt(0) + r) at column left = r and column right = width - 1 - r inside a grid of width 2*rows - 1.
On the final row left equals right at the center column. The condition c == left || c == right is true for only one column, so one letter prints - not two.
For row index r (0-based), left = r moves down-right. right = width - 1 - r moves down-left. They converge at the center when r equals rows - 1.
The X needs equal space on both sides of the center. For rows=5 the widest row has A at columns 0 and 8, so width is 9 = 2*5 - 1.
Each row uses letters starting at A through the r-th letter. With rows > 26 you would need characters beyond Z unless you define a wrap policy.
line += ch (or a space) stays on the same row with no newline between characters. console.log(line) ends the row after the column loop finishes.
O(n^2) where n is rows. There are n rows and each row scans width = 2*n - 1 columns.
Use parseInt(prompt(), 10) and check Number.isFinite, then clamp rows between 1 and 26.

Did you Know? 🔊

Row r prints letter String.fromCharCode('A'.charCodeAt(0) + r) at columns left = r and right = width - 1 - r in a grid of width 2*rows - 1. On the last row both diagonals meet, so only one E appears in the center.

Continue to Program 32

Next up: the centered alphabet palindrome pyramid - build on symmetric shape ideas from this tutorial.

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