JavaScript Star Cross Pattern (Over Zeros)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

An X pattern of * and 0 fills a grid: stars on both diagonals and the center column; zeros everywhere else.

Remember
Rule: * if i===j or j===mid or i===cols+1-j; else 0

*000*000*
0*00*00*0
00*0*0*00
000***000   ← rows = 4, cols = 9

Unlike Program 44 (number diamond), this pattern visits every cell and chooses a character with a three-part condition — total cells = rows × cols.

How to Solve It

Nest loops over rows and columns. Compute mid, then append * or 0. End each row with console.log.

MethodIdeaBest for
Diagonals + midi===j / j===mid / anti-diagonalClassic X demos
Diagonals onlyDrop the j===mid checkPure X contrast

Pseudocode

Pseudocode
mid = floor((cols + 1) / 2)
for i from 1 to rows:
    line = ""
    for j from 1 to cols:
        if i == j or j == mid or i == cols + 1 - j:
            append "*"
        else:
            append "0"
    print line

Cheat sheet

GoalPattern
Walk gridfor (let i = 1; i <= rows; i++) / for (let j = 1; j <= cols; j++)
Center columnconst mid = Math.floor((cols + 1) / 2);
Star testi === j || j === mid || i === cols + 1 - j
Star / zeroline += "*"; / line += "0";
End the rowconsole.log(line);

Printing Numbers vs Starting a New Line

APIEffectUse for
line += …Stays on the same rowEach cell (* or 0)
console.log(line)Ends the current rowAfter all columns in the row

Append without a newline, then end the row once.

Live Preview

Change the row count (width becomes 2 × rows + 1) and the X updates instantly.

Whole numbers from 3 to 6. Columns = 2 × rows + 1 (odd width so the center column exists). Tap a chip or type a value — the preview redraws as you go.

Live result 4 × 9 · 36 cells
*000*000*
0*00*00*0
00*0*0*00
000***000

Worked Walkthrough

With rows = 4, cols = 9, mid = 5 — trace why key cells print *.

CellWhy *?Rule
(1,1)main diagonali === j
(1,5)center columnj === mid
(1,9)anti-diagonali === cols + 1 - j
(4,5)diagonal + mid meetall three can match

Every cell is decided once — total appends = rows × cols.

JavaScript Programs

Three complete programs: fixed 4×9, prompt size, and diagonals-only contrast. Use View Output for samples, or Try It Yourself to edit and run live.

Example 1 — Fixed rows = 4, cols = 9

Hard-coded size — diagonals plus center column of stars.

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

1. Walk the grid. Outer loop is rows; inner loop is columns — both 1-based.

2. Find the center. mid = Math.floor((cols + 1) / 2) is column 5 when cols = 9.

3. Three star rules. Main diagonal (i === j), center column (j === mid), anti-diagonal (i === cols + 1 - j).

Example 2 — User Input Size

Read rows and odd cols with prompt, then compute mid.

JavaScript
const rows = parseInt(prompt("Enter rows:"), 10);
const cols = parseInt(prompt("Enter cols (odd):"), 10);

if (!Number.isFinite(rows) || rows < 1 ||
    !Number.isFinite(cols) || cols < 1 || cols % 2 === 0) {
  console.log("Need positive rows and an odd cols.");
} else {
  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

1. Prompt and validate. Require positive rows and an odd cols so a true center column exists.

2. Derive mid and anti-diagonal. mid and cols + 1 - j replace hard-coded 5 and 10 - j.

3. Same star core. Only the source of size changes — the if condition matches Example 1.

Example 3 — Diagonals Only

Same grid; drop the center-column check for a pure X.

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

1. Two conditions only. Keep main and anti-diagonals; remove j === mid.

2. Center fills with zeros. Column 5 is no longer forced to * (except where a diagonal crosses it).

3. Clear contrast. Compare with Example 1 to see what the mid check added.

Edge Cases & Pitfalls

Check these before calling the solution done.

even cols

Prefer odd cols

Even width has no single center column. Prefer odd cols so mid is exact.

0-based

Adjust anti-diagonal if indices start at 0

For 0-based loops use i + j === cols - 1 instead of i === cols + 1 - j.

rows > cols

More rows than columns

The main diagonal exits the grid early. Keep rows <= cols for a clear X.

Bad input

Validate parseInt

Check Number.isFinite, require rows >= 1, and insist on odd cols.

Time and Space Complexity

ProgramTimeExtra space
Fixed / diagonals (Examples 1, 3)O(rows × cols)O(cols) per row string
User input (Example 2)O(rows × cols)O(cols) per row string

Every cell of the grid is visited once, so work is proportional to the product of rows and columns.

Key Takeaways

  • Rule: * on diagonals and mid column; 0 elsewhere.
  • Size: prefer odd cols; mid = Math.floor((cols + 1) / 2); anti-diagonal uses cols + 1 - j.
  • Break the row: call console.log(line) only after all columns finish.
  • Complexity: O(rows × cols) — visit every cell once.

One line: nest two loops, append * on diagonals and mid, append 0 elsewhere, then log each row.

Frequently Asked Questions

An X-style grid: * on both diagonals and the center column, with 0 filling the remaining cells (classic demo: 4×9).
With cols = 9, mid = Math.floor((cols + 1) / 2) = 5. Checking j === mid draws the vertical center line.
Main diagonal: i === j. Anti-diagonal: i === cols + 1 - j (for cols = 9 that is i === 10 - j).
line += appends on the same row. console.log(line) ends the row after all columns finish.
Program 44 prints a centered number diamond. Program 45 prints a rectangular * / 0 grid using diagonal and center conditions.
Yes — drop the j === mid check for a pure X of diagonals only — see Example 3.
O(rows × cols) because each cell is visited once.
Odd width gives a true single center column for mid. Even cols have no exact middle.

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.

Next: Concentric Number Square

Continue with 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