Diamond Alphabet & Stars in JavaScript

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

What You’ll Learn

Build a vertical diamond where each row repeats the same letter, with * between letters. The pattern widens to the middle row, then mirrors back down — A, B*B, C*C*C, …, E*E*E*E*E, then back to A. Compare Program 15 (stars in the center) and Program 19 (mirrored letters with spaces). Includes a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Vertical diamond

Widen 1..n, then mirror n-1..1 without duplicating the middle.

Row Letter

One per row

Row i uses letter String.fromCharCode("A".charCodeAt(0) + i - 1) (or alpha[i-1]).

Odd Length

2i − 1

Inner loop prints 1, 3, 5, … characters per row.

Alternate

j % 2

Odd positions print the letter; even positions print *.

Live Preview

Half height

Pick half height 1–8 and draw the diamond instantly.

O(n²)

Complexity

Odd-length rows up and down sum to O(n²).

Introduction

A diamond alphabet pattern with stars repeats one letter on each row and places * between those letters, widening to a middle row and then mirroring back down.

In JavaScript you usually solve it with two outer loops (upper and lower halves) and an inner loop that uses j % 2 to choose letter vs star.

Why it matters?

It teaches three classic ideas at once: odd row lengths, position-based alternation, and mirroring without duplicating the widest row.

Key Highlights

Upper + Lower

Grow to n, then mirror from n-1.

Odd Widths

Rows have 1, 3, 5, … characters.

j % 2

Letter on odd, * on even.

One Letter / Row

Row i repeats letter number i.

In short: for each half-height row, append 2i-1 characters alternating letter and *, then mirror from n-1 down to 1.

📝 Problem & Approach

Given a half height n (or fixed 5), print a vertical diamond of alternating letters and stars.

JavaScript
# Half height 5
# A
# B*B
# C*C*C
# D*D*D*D
# E*E*E*E*E
# D*D*D*D
# C*C*C
# B*B
# A

Inputs & Outputs

ItemTypeDescription
nintHalf height (middle row letter = ‘A’ + n − 1). Cap at 26 for A–Z.
Printed outputtextAbout 2n-1 rows of letter/* patterns forming a diamond.

Minimal workflow

Pseudocode
for i in 1..n:
    ch = 'A' + i - 1
    line = ""
    for j in 1..(2i-1):
        line += (j even ? "*" : ch)
    console.log(line)
for i in (n-1)..1:
    (same inner loop)

Approach comparison

ApproachIdeaBest for
Two outer halves1..n then n-1..1Matching this classic sample
Helper functionExtract “print row i” onceAvoiding duplicated inner loops
join rewrite"*".join([ch]*i) styleJavaScriptic one-liner per row

⚡ Quick Reference

GoalPattern
Upper halffor (let i = 1; i <= n; i++)
Lower halffor (let i = n - 1; i >= 1; i--)
Row lengthfor (let j = 1; j < i * 2; j++)2i-1 chars
Alternateline += (j % 2 === 0 ? "*" : ch)
Row letterch = String.fromCharCode("A".charCodeAt(0) + i - 1) or alpha[i - 1]
End the rowconsole.log(line)

📋 Letter vs Star vs console.log

Same row — different roles by column index.

Odd j
letter

Prints the current row letter (A, B, C…)

Even j
*

Prints the separator between letters

2i-1
width

Odd length so the row ends on a letter

console.log
break

Ends the row after the alternating run

Context

When This Pattern Shows Up

Reach for this when teaching vertical mirrors and position-based alternation.

  1. After mirrored rows

    You already know half-and-mirror; now alternate symbols inside each row.

  2. Modulo drills

    Practice j % 2 for clean letter/star placement.

  3. Odd-length growth

    Same 1, 3, 5… idea used in many pyramids and diamonds.

  4. Separator swaps

    Replace * with - or spaces for variant labs.

  5. Not a UI layout tool

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

Key benefit: one modulo check plus a careful lower-half start builds a clean vertical diamond.

🔮 Live Preview

Choose a half height between 1 and 8 and draw the diamond alphabet-and-stars pattern in the browser.

Try 5 (classic through E) or 3 (through C). Max 8 keeps the preview readable.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs - fixed half height 5, user-chosen half height, and a helper / join rewrite. Click View Output to reveal sample console results, or Try it Yourself to run in the browser editor.

📚 Getting Started

Print the classic diamond with a letter string and two halves.

Example 1 — Fixed Half Height 5

Odd j appends the row letter; even j appends *. Upper half prints 1..5, lower half prints 4..1.

JavaScript
const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for (let i = 1; i <= 5; i++) {
  let line = "";
  for (let j = 1; j < i * 2; j++) {
    line += (j % 2 === 0) ? "*" : alpha[i - 1];
  }
  console.log(line);
}

for (let i = 4; i >= 1; i--) {
  let line = "";
  for (let j = 1; j < i * 2; j++) {
    line += (j % 2 === 0) ? "*" : alpha[i - 1];
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 3, the inner loop runs j = 1..5 and appends C * C * C. The lower half starts at 4 so E*E*E*E*E appears only once.

📈 Practical Variant

Let the user choose the half height.

Example 2 — Half Height Input

Uses a computed row letter instead of an index into a string. Validate parseInt(prompt()) with Number.isFinite in real apps.

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

  for (let i = 1; i <= n; i++) {
    const ch = String.fromCharCode(base + i - 1);
    let line = "";
    for (let j = 1; j < i * 2; j++) {
      line += (j % 2 === 0) ? "*" : ch;
    }
    console.log(line);
  }

  for (let i = n - 1; i >= 1; i--) {
    const ch = String.fromCharCode(base + i - 1);
    let line = "";
    for (let j = 1; j < i * 2; j++) {
      line += (j % 2 === 0) ? "*" : ch;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same alternation and mirror rules; only n changes the size. Math.max(1, Math.min(n, 26)) keeps row letters within A–Z.

⚡ Cleaner Structure

Extract the row printer or use a join-based one-liner per row.

Example 3 — printRow Helper / join Rewrite

Same diamond, less duplicated code. The join version builds each row as ch + "*" + ch + ... in one expression.

JavaScript
function printRow(i) {
  const ch = String.fromCharCode("A".charCodeAt(0) + i - 1);
  console.log(Array(i).fill(ch).join("*"));
}

const n = 5;

for (let i = 1; i <= n; i++) {
  printRow(i);
}

for (let i = n - 1; i >= 1; i--) {
  printRow(i);
}
Try it Yourself

How It Works

Array(i).fill(ch).join("*") repeats the letter i times and inserts * between them - same visual as the j % 2 loop. The two outer loops only decide which row heights to print.

🧠 How the Algorithm Prints Rows

1

Upper half: 1 to n

The first outer loop runs i = 1..n, making the row length grow.

Up
2

Odd/even positions alternate

Inner loop prints 2i-1 characters: odd j prints the letter, even j prints *.

Alternate
3

Lower half mirrors down

Second outer loop runs i = n-1..1 so the widest row is not duplicated.

Mirror
4

New line

console.log(line) ends each row after the alternating run.

Break
=

Diamond made from rows

Total printed characters scale like O(n²) for half height n.

🔎 Worked Walkthrough — n = 3

Trace each half and the characters printed on each row.

HalfiLetterChars (2i−1)Printed row
Upper1A1A
Upper2B3B*B
Upper3C5C*C*C
Lower2B3B*B
Lower1A1A

Total rows: 2n - 1 = 5. Middle row C*C*C appears once.

Use Cases

Where this diamond letter/star idea shows up beyond the homework prompt.

1. Alternation Practice

Clearest alphabet demo of j % 2 choosing two symbols.

Example: swap * for - and compare.

2. Mirror Without Duplicates

Practice starting the lower half at n-1.

Example: start at n once and see the doubled middle.

3. Helper Extraction

Refactor duplicated halves into print_row (Example 3).

Example: one function, two calling loops.

4. Centered Diamond Labs

Add leading spaces later for a true 2D diamond silhouette.

Example: pad with n - i spaces before each row.

5. Complexity Intuition

Odd sums up and down make O(n²) easy to see.

Example: n=5 prints 25 + 16 = 41 characters.

6. Alphabet Caps

Practice limiting half height so letters stay in A–Z.

Example: reject n > 26 or clamp it.

Pro Tip: say “odd letter, even star, mirror from n minus one” before coding — that story prevents a doubled middle row.

Advantages

Why this pattern earns a spot among diamond and separator labs.

  1. 1. Instant Visual Feedback

    Wrong modulo or a duplicated middle row shows up immediately.

  2. 2. Tiny Alternation Rule

    One j % 2 check drives the whole letter/star effect.

  3. 3. Easy to Refactor

    A small helper or join rewrite removes duplicated upper/lower inner loops.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop variables.

Pro Tip: get the upper half right first; only then add the lower half starting at n-1.

Usage Tips

Small habits that keep diamond letter/star code clean.

  1. 1. Start Lower Half at n-1

    That single off-by-one avoids duplicating the widest row.

  2. 2. Keep Odd Row Lengths

    Use 2i-1 so every row ends on a letter, not a star.

  3. 3. Use Number.isFinite

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

  4. 4. Cap at 26

    Beyond Z you need a wrap/stop policy for row letters.

  5. 5. Extract print_row

    Share one inner loop or join expression between upper and lower halves.

Pro Tip: if the middle letter row appears twice, you almost certainly started the lower half at n instead of n-1.

Common Pitfalls

Mistakes that commonly break diamond alphabet-and-star patterns.

  1. 1. Starting Lower Half at n

    Duplicates the widest row in the middle.

    → Start from n - 1.

  2. 2. Even Row Length

    Ending on a star breaks the letter-star-letter rhythm.

    → Print exactly 2i - 1 characters.

  3. 3. Flipped Modulo

    Printing stars on odd positions yields *B* instead of B*B.

    → Letter on odd j, star on even j.

  4. 4. Blind parseInt(prompt())

    Letters or empty input raise NaN.

    → Use Number.isFinite and re-prompt on failure.

  5. 5. Overflowing Z

    Large half heights walk past the alphabet.

    → Cap n at 26 or define a wrap policy.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single letter

Output is just A; lower half does not run.

n = 5

Classic sample

Middle row is E*E*E*E*E.

n = 3

Small diamond

Five rows through C*C*C.

n > 26

Past Z

Reject, clamp, or wrap — decide explicitly.

Bad input

Non-numeric prompt()

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

Separator

- or space

Same loops; only the even-position character changes.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change the separator

  • Print - instead of *
  • Keep odd letter positions

2. Center the diamond

  • Add n - i leading spaces
  • Compare silhouette to star diamonds

3. Extract print_row

  • Refactor like Example 3
  • Share one inner loop or join

4. Continue to Program 22

  • Right-aligned sequential alphabet pyramid
  • See Program 22

Notes

  • Middle once. Lower half starts at n-1 so the widest row is not repeated.
  • Row length is always odd (2i-1) so rows end on a letter.
  • Odd j → letter; even j*.
  • Total rows = 2n - 1 for half height n.

Quick Takeaway: print odd-length letter/star rows from 1 to n, then mirror from n-1 to 1 — that is the whole diamond.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Helper / join (Example 3)O(n²)O(1)

Upper half prints about n² characters (sum of odds); lower half adds almost the same without the middle row — still O(n²).

Wrap Up

🎉 Conclusion

The diamond alphabet-and-stars pattern is a small nested-loop exercise with lasting payoff: odd row lengths, position-based alternation, and a careful vertical mirror. Master the classic A…E…A sample, then try user input and a helper/join rewrite.

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

Print 2i-1 characters with letter on odd positions and * on even ones, grow to n, then mirror from n-1.

💡 Best Practices

✅ Do

  • Start the lower half at n - 1
  • Use odd row lengths (2i - 1)
  • Print letters on odd j, stars on even j
  • Use Number.isFinite and cap at 26
  • Extract a row helper when halves share logic

❌ Don’t

  • Start the lower half at n (duplicates middle)
  • Use an even character count per row
  • Flip the modulo unless you want star-first rows
  • Ignore alphabet overflow on large n
  • Call console.log(line) inside the alternating loop

Key Takeaways

Knowledge Unlocked

Five things to remember about this alphabet pattern

Print the diamond alphabet-and-stars pattern the beginner-friendly way.

5
Core concepts
% 02

Alternate

j % 2 letter/*

Code
2i 03

Width

2i − 1 chars

Code
n-1 04

Mirror

Lower starts here

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

j runs 1,2,3,... Odd positions print the row letter and even positions print '*', producing lines like B*B and C*C*C.
The inner loop checks the position: even columns print '*', odd columns print the row letter. That alternates symbols cleanly.
That prints 2*i-1 characters per row (1,3,5,...), which makes the pattern widen toward the center.
The upper half already printed the widest row at i=n. Starting from n-1 mirrors without duplicating the middle row.
line += ch or line += '*' stays on the same conceptual row for each letter or star. console.log(line) ends the row after the inner loop finishes.
Program 15 puts stars in the center of a symmetric alphabet row. This pattern repeats one letter per row and places stars between those letters, then mirrors vertically.
O(n^2) for half height n because the total printed characters is proportional to 1+3+...+(2n-1) up and down.
Use parseInt with Number.isFinite after prompt(), require n >= 1, and cap at 26 so row letters stay within A-Z.

Did you Know? 🔊

Upper half prints rows 1..n; lower half prints n-1..1 so the widest row appears once. Each row runs j = 1..(2i-1). Odd j prints the row letter, even j prints *.

Continue to Alphabet Pattern 22

Next up: right-aligned sequential alphabet pyramids with a running letter counter.

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