X Pattern with 0 and * in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Conditions + Nested Loops

What You’ll Learn

Program 45 prints an X-style grid: * on both diagonals and the center column, 0 everywhere else on a 4 × 9 rectangle — a natural step after Program 44’s centered number diamond. This tutorial covers nested loops with multi-condition checks, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

* on X + center

* when on a diagonal or center column; 0 fills every other cell.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) walks each row of the grid.

Inner Loop

j = 1..cols

for (let j = 1; j <= cols; j++) walks each column within the current row.

Three Checks

Diagonals + mid

i === j || j === mid || i === cols + 1 - j appends *; else append 0.

Live Preview

4×9 default

Adjust rows and odd column width, then draw the star-and-zero X in the browser.

O(rows×cols)

Complexity

Each cell visited once — rows × cols prints; extra memory stays O(1).

Introduction

A star-and-zero X pattern prints * on both diagonals and the center column, filling every other cell with 0. With rows = 4 and cols = 9, the output forms a compact cross on a rectangular grid.

In JavaScript the outer loop runs i = 1..rows, the inner loop runs j = 1..cols, and a three-part condition uses line += "*" or line += "0" per cell.

Why it matters?

It teaches diagonal math and multi-condition checks on a 2D grid — a key step after Program 44’s centered diamond.

Key Highlights

Main diagonal

i === j left-to-right.

Anti-diagonal

i === cols + 1 - j.

vs Program 44

Program 44 prints ascending digits in a diamond; Program 45 prints * and 0 on a fixed grid.

Series Foundation

Follow Program 44; continue to Program 46 next.

In short: nested loops over i, j, three-way check appends *, else 0, then console.log(line).

📝 Problem & Approach

Given a 4 × 9 grid, print * on both diagonals and the center column; fill remaining cells with 0.

JavaScript
// rows = 4, cols = 9
//*000*000*
//0*00*00*0
//00*0*0*00
//000***000

Inputs & Outputs

ItemTypeDescription
rowsnumberNumber of rows (e.g. 4).
colsnumberNumber of columns (e.g. 9 — odd width gives a clear center).
midnumberCenter column: Math.floor((cols + 1) / 2) (e.g. 5 when cols is 9).
inumberOuter loop — current row index (1 to rows).
jnumberInner loop — current column index (1 to cols).

Minimal workflow

Pseudocode
mid = Math.floor((cols + 1) / 2)
for i from 1 to rows:
    for j from 1 to cols:
        if (i === j || j === mid || i === cols + 1 - j):
            append "*"
        else:
            append "0"
    console.log(line)

Approach comparison

ApproachIdeaBest for
Nested loops + condition*000*000* fixed 4×9Learning and interviews
Parameterized rows/colsmid = Math.floor((cols + 1) / 2)Flexible rectangular grids
Diagonals onlyDrop j === mid checkPure X without center line

⚡ Quick Reference

GoalPattern
Walk rowsfor (let i = 1; i <= rows; i++)
Walk columnsfor (let j = 1; j <= cols; j++)
Center columnmid = Math.floor((cols + 1) / 2)
Star checkif (i === j || j === mid || i === cols + 1 - j)
Append starline += "*"
Append fillline += "0"
Program 44 contrastCentered number diamond with ascending digits — not a star/zero grid

📋 Fixed Grid vs Parameterized vs Diagonals Only

Same star-and-zero X — different ways to control dimensions and which lines print stars.

Outer loop
i = 1..rows

Rows of the grid

Inner loop
j = 1..cols

Columns per row

Center
mid = (cols+1)/2

Vertical line column

Condition
i==j or j==mid

Three-way star check

Context

When This Pattern Shows Up

Reach for this pattern when teaching 2D grids, diagonal math, and multi-condition cell checks.

  1. Post Program 44 exercise

    Natural follow-up after Program 44 — same nested loops but adds diagonal and center conditions.

  2. Diagonal coordinate drills

    Practice i === j and i + j === cols + 1 on paper before coding.

  3. Rectangular grids

    Unlike square patterns, rows and cols can differ — center column needs odd width.

  4. Gateway to variants

    Compare Program 44 (number diamond) and Program 46 (next in series) next.

  5. Not a UI layout tool

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

Key benefit: one small program that locks in nested loops, diagonal conditions, and O(rows×cols) thinking.

🔮 Live Preview

Set rows (3–6) and odd column width (7–11), then draw the star-and-zero X in the browser.

Try 4×9 (default) or 5×11. Columns should be odd for a clear center.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed grid, parameterized dimensions, and diagonals-only contrast. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print a 4×9 star-and-zero X with nested loops and a three-part condition.

Example 1 — Fixed rows = 4, cols = 9

Hard-coded grid dimensions — ideal for first demos and screenshots.

JavaScript
const rows = 4;
const cols = 9;
const mid = 5; // middle column (1-based)

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= cols; j++) {
    if (i === j || j === mid || i === cols + 1 - j) {
      line += "*";
    } else {
      line += "0";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 1 and j = 1, i === j is true — appends *. When i = 2 and j = 5, j === 5 hits the center column — appends *. All other cells append 0.

📈 Parameterized Grid

Use rows, cols, and mid instead of hard-coded 4, 9, and 5.

Example 2 — Variable Rows and Columns

Compute mid with Math.floor((cols + 1) / 2) and use (cols + 1) - j for the anti-diagonal.

JavaScript
const rows = 4;
const cols = 9;
const mid = Math.floor((cols + 1) / 2);

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= cols; j++) {
    if (i === j || j === mid || i === cols + 1 - j) {
      line += "*";
    } else {
      line += "0";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

Same inner-loop core as Example 1; mid replaces the literal 5, and (cols + 1) - j replaces 10 - j. Change rows or cols to resize the pattern.

⚡ Diagonals Only

Drop the center-column check for a pure X without the vertical line.

Example 3 — Diagonals Only (No Center Column)

Remove j === mid from the condition — only the two diagonals append stars.

JavaScript
const rows = 4;
const cols = 9;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = 1; j <= cols; j++) {
    if (i === j || i === cols + 1 - j) {
      line += "*";
    } else {
      line += "0";
    }
  }
  console.log(line);
}
Try it Yourself

How It Works

Without the center column, row 4 no longer prints 000***000 — it becomes 000*0*000. Compare with Example 1 to see how one condition changes the shape.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set rows = 4, cols = 9, and loop variables i, j for the grid.

Setup
2

Nested loops build grid

for (let i = 1; i <= rows; i++) and for (let j = 1; j <= cols; j++) visit every cell in the grid.

Grid
3

Star check

if (i === j || j === mid || i === cols + 1 - j) — true on a diagonal or center column.

Condition
4

Append star or zero

Matching cells use line += "*"; all others use line += "0".

Output
5

New line

console.log(line) ends each row after the inner loop finishes.

Break
=

Star-and-zero X complete

Every cell visited once — O(rows×cols) time, O(1) extra memory.

🔎 Worked Walkthrough — row i = 3, cols = 9

Trace each column j on row 3 — which cells match a diagonal or center condition.

jConditionPrints
1No0
2No0
3i === j*
4No0
5j === mid*
6No0
7i === cols + 1 - j*
8No0
9No0

Row 3 output: 00*0*0*00 — stars at columns 3, 5, and 7. Total cells = rows × cols = 36 for a 4×9 grid.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: swap 0 for . or space — see FAQ.

2. Pattern Series Base

Foundation for X patterns, cross grids, and diagonal-only variants.

Example: continue to Program 46 for the next pattern in the series.

3. Console Formatting Drills

Practice line += vs console.log(line) without complex math.

Example: put console.log(line) inside the inner loop by mistake.

4. Diagonal Math

Learn why i === j and i + j === cols + 1 mark the two diagonals.

Example: trace row i = 3 in the walkthrough table.

5. Complexity Intuition

Rectangular totals make O(rows×cols) concrete for beginners.

Example: count star cells for 4×9 — total grid cells = 36.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row validation.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Drop center column, change fill char, or resize rows/cols with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 3 and each j on paper — watch how one cell can match multiple conditions at intersections.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Use rows, cols, and mid

    Never hard-code 5 or 10 — use mid and (cols + 1) - j everywhere.

  2. 2. Validate with Number.isFinite

    Use Number.isFinite so bad prompt() input does not crash when converting dimensions.

  3. 3. Keep console.log(line) Outside

    Only call console.log(line) after the inner loop finishes the row.

  4. 4. Odd Column Width

    Use odd cols so mid = Math.floor((cols + 1) / 2) lands on a single center column.

  5. 5. Dry-Run row i = 3

    Trace columns j = 1..9 on paper before coding the full 4×9 demo.

Pro Tip: if the output is a vertical list of single characters per line, you almost certainly put console.log(line) inside the inner loop.

Common Pitfalls

Mistakes that commonly break star-and-zero X patterns.

  1. 1. Newline Inside the Inner Loop

    Each cell lands on its own line — you get a column, not a square.

    → Use line += "*" or line += "0" per cell; console.log(line) only after the inner loop.

  2. 2. Hard-Coded Diagonal Formula

    Using 10 - j breaks when cols changes from 9 to 11 or 7.

    → Always use (cols + 1) - j for the anti-diagonal.

  3. 3. Forgetting Center Column

    Only checking diagonals gives a pure X — missing the vertical line in the full pattern.

    → Add j === mid where mid = Math.floor((cols + 1) / 2).

  4. 4. Even Column Width

    Even cols has no single middle column — mid may not align as expected.

    → Prefer odd column counts (7, 9, 11) for a clear center line.

  5. 5. Bare parseInt(prompt())

    Letters or empty input yield NaN with bare parseInt(prompt()).

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

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

One row of stars and zeros — diagonals collapse to corner cells only.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Even cols

No clear center

Even column width has no single middle — center line may look off.

cols = 7

Compact grid

Smaller width — mid = 4, anti-diagonal uses 8 - j.

Bad input

Non-numeric input

Bare parseInt(prompt()) yields NaN on bad input — use Number.isFinite first.

Large rows

Large row count

Each cell visited once — total work grows as rows × cols.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Number diamond

  • Review Program 44’s centered digit diamond
  • Compare with Program 44

2. Pure X only

  • Remove j === mid from the condition
  • Same nested loops — see Example 3

3. Next in series

  • Continue with Program 46
  • Build on diagonal grid logic

4. Custom fill

  • Use . or space instead of 0
  • Same condition, different fill character

Notes

  • Star rule. Append * when i === j || j === mid || i === cols + 1 - j; else append 0.
  • Build each row with line +=, then console.log(line) once per row.
  • Prefer odd cols for a clear center column; compute mid = Math.floor((cols + 1) / 2).
  • A rows × cols grid has rows × cols cells — each visited exactly once.

Quick Takeaway: nested loops over i, j, three-way check appends *, else 0, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(rows × cols)O(1)
Smaller demo (Example 3)O(rows × cols)O(1)
Wrap Up

🎉 Conclusion

The star-and-zero X pattern is a compact nested-loop lesson: visit every cell in a rectangular grid and use a three-part condition to print * or 0. Master the fixed 4×9 version, then try parameterized dimensions and the diagonals-only variant.

Practice the three examples above, then continue to Program 46 for the next pattern in the series.

Diagonals use i === j and i === cols + 1 - j — add j === mid for the center column and prefer odd column width.

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= rows; i++) and for (let j = 1; j <= cols; j++)
  • Star: if (i === j || j === mid || i === cols + 1 - j)
  • Append "*" on match, "0" elsewhere with line +=
  • Compute mid = Math.floor((cols + 1) / 2) for center column
  • Prefer odd cols for a clear vertical line

❌ Don’t

  • Call console.log(line) inside the inner cell loop
  • Hard-code 10 - j when cols can change
  • Forget j === mid if you want the center column
  • Use even column width without adjusting expectations
  • Skip tracing row i = 3 before coding

Key Takeaways

Knowledge Unlocked

Five things to remember about this star-and-zero X pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Rows i = 1..rows

Code
03

Inner loop

Columns j = 1..cols

Code
04

Condition

i==j or j==mid

Logic
O 05

Complexity

O(rows×cols)

Analysis

❓ Frequently Asked Questions

An X-style pattern using * on the two diagonals and the center column, filling remaining positions with 0 on a 4x9 grid.
The width is 9 columns (j = 1..9). The middle column is 5, so checking j === 5 prints a vertical center line.
The left-to-right diagonal uses i === j. The right-to-left diagonal uses i === cols + 1 - j (10 - j when cols is 9).
Program 44 prints a centered number diamond with ascending digits. Program 45 prints a fixed grid with * and 0 using diagonal and center conditions.
Use rows and cols variables, compute mid = Math.floor((cols + 1) / 2), and use (cols + 1) - j for the anti-diagonal — see Example 2.
O(rows × cols) because each cell is visited once in the nested loops.
Yes — drop the j === mid check to get a pure X of diagonals only — see Example 3.
For 1-based indexing, row i meets column j on the anti-diagonal when i + j equals cols + 1.
Any single character works in the else branch — try . or space for a different look.
Use parseInt with Number.isFinite and validate rows > 0 and odd cols when needed.

Did you Know? 🔊

Append * when i === j, j === mid, or i === cols + 1 - j; otherwise append 0. A rows × cols grid visits every cell once — total appends = rows × cols.

Continue to Program 46

Move on to the next pattern in the JavaScript number-pattern series.

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