Star Cross Pattern with 0s in Java

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

What You’ll Learn

The star cross pattern fills a grid with 0s and prints * on the main diagonal, anti-diagonal, and middle column. This tutorial covers the three conditions, nested loops, live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Three conditions

Print * when i==j, j==mid, or i==cols+1-j; otherwise print 0.

Column Loop

j = 1..cols

for (j = 1; j <= cols; j++) walks every column in the current row.

Cross Check

mid column

mid = cols / 2 + 1 locates the center column when cols is odd (e.g. 9 → 5).

Outer Loop

Row index i

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

Live Preview

1–12 rows

Pick a row count and draw the star cross pattern instantly in the browser (columns fixed at 9).

O(rows×cols)

Complexity

Visits every cell once — rows×cols iterations; extra memory stays O(1).

Introduction

A star cross pattern with 0s prints * on the main diagonal, anti-diagonal, and middle column; every other cell prints 0. With rows = 4 and cols = 9, the last row becomes 000***000.

In Java you use nested loops (i = 1..rows, j = 1..cols) and a three-part if that picks * or 0 for each cell.

Why it matters?

It combines diagonal math with a center-column check — a classic grid pattern after number diamonds.

Key Highlights

Main Diagonal

i == j draws the top-left to bottom-right line.

Anti-Diagonal

i == cols + 1 - j completes the X shape.

Middle Column

j == mid adds the vertical line through the center.

Series Foundation

Follow Program 44 number diamond; continue to Program 46 concentric square.

In short: nested row/column loops, three-part if for *, else 0; call System.out.println() after each row.

📝 Problem & Approach

Given rows = 4 and cols = 9, print a grid where * marks the X and middle column; all other cells are 0.

Java
// rows = 4, cols = 9 (conceptual shape)
// *000*000*
// 0*00*00*0
// 00*0*0*00
// 000***000

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows in the grid (typically ≥ 1).
colsintNumber of columns (9 in the classic example; odd width gives one center column).
Printed outputtextrows × cols characters — * on cross lines, 0 elsewhere.

Minimal workflow

Pseudocode
mid = cols / 2 + 1
for i from 1 to rows:
    for j from 1 to cols:
        if i==j or j==mid or i==cols+1-j: print *
        else: print 0
    print newline

Approach comparison

ApproachIdeaBest for
Three-condition grid*000*000* first row with X + mid columnLearning and interviews
User-input rowssc.nextInt(); with fixed cols = 9Flexible console programs
X-only crossDrop j == mid — diagonals onlyContrast with full cross

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Walk columnsfor (j = 1; j <= cols; j++)
Cross ifi==j || j==mid || i==cols+1-j
Center columnmid = cols / 2 + 1
End the rowSystem.out.println();
Program 44 contrastNumber diamond uses mirrored rows; this pattern uses a fixed grid with diagonal checks

📋 Diagonal vs Middle vs Combined

Same grid cell — how the three cross conditions pick * or 0.

Cross check
i == j

Main diagonal — top-left to bottom-right

Anti-diagonal
i == cols+1-j

Secondary diagonal for the X shape

Middle column
j == mid

Vertical line through center (mid = cols/2+1)

Learning tip
trace i=2,j=5

Dry-run cell (2,5): mid column → prints *

Context

When This Pattern Shows Up

Reach for this pattern when teaching diagonal conditions inside a full row×column grid.

  1. First lab exercise

    Classic follow-up after diamonds and symbol grids.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible row count.

  4. Gateway to variants

    Compare with Program 44 (number diamond), then continue to Program 46 (concentric square).

  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, output sequencing, and O(rows×cols) thinking.

🔮 Live Preview

Choose a row count (columns fixed at 9) and draw the star cross pattern in the browser.

Columns stay at 9. Try 3, 4, or 6 rows (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed row count, Scanner input, and an X-only cross variant. Click View Output to reveal sample console results.

📚 Getting Started

Print four rows over nine columns with nested loops and a three-part if.

Example 1 — Fixed rows = 4, cols = 9

Hard-coded size — nested loops and the cross check build each row.

Java
public class StarCrossPattern {
    public static void main(String[] args) {
        int rows = 4;
        int cols = 9;
        int mid = cols / 2 + 1;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                if (i == j || j == mid || i == cols + 1 - j) {
                    System.out.print("*");
                } else {
                    System.out.print("0");
                }
            }
            System.out.println();
        }
    }
}

How It Works

When i = 1, j = 1, the main-diagonal check prints *. When i = 2, j = 5, the middle-column check prints * while neighbors print 0.

📈 Practical Variant

Let the user choose the row count at runtime (columns stay at 9).

Example 2 — User Input Version

Read the row count with Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class StarCrossPatternInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();
        int cols = 9;
        int mid = cols / 2 + 1;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                if (i == j || j == mid || i == cols + 1 - j) {
                    System.out.print("*");
                } else {
                    System.out.print("0");
                }
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Remove the middle-column check for a plain X without the vertical center line.

Example 3 — X-Only Cross

Remove the middle-column check to print a plain X without the vertical center line.

Java
public class StarCrossXOnly {
    public static void main(String[] args) {
        int rows = 4;
        int cols = 9;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                if (i == j || i == cols + 1 - j) {
                    System.out.print("*");
                } else {
                    System.out.print("0");
                }
            }
            System.out.println();
        }
    }
}

How It Works

Same nested-loop grid; dropping j == mid leaves only the two diagonals that form the X.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows, cols = 9, and mid = cols / 2 + 1.

Setup
2

Outer loop (rows)

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

Row
3

Inner loop (columns)

for (j = 1; j <= cols; j++) visits every column in the current row.

Column
4

Inner loop + if

Three checks print *; else 0, then println() ends the row.

Cells
=

Star cross pattern with 0s complete

Total cell visits equal rows×colsO(rows×cols) time, O(1) extra memory.

🔎 Worked Walkthrough — cell i = 2, j = 5

Trace one center-column cell to see the three checks in action.

CheckResultPrints
i == j (2==5)false
j == mid (5==5)true*
i == cols+1-j (2==5)false

Cell output: * — full grid visits: 4×9 = 36 = rows×cols.

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: drop j == mid and get an X-only cross instead.

2. Pattern Series Base

Foundation for symbol grids, diagonal patterns, and cross variants.

Example: swap * and 0 for 1 and 0 to build a number cross.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap * and 0 for other symbols once the loop works.

Example: replace * with 1 and keep 0 as fill.

5. Complexity Intuition

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

Example: count cells for rows=4, cols=9 → 36 visits.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

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 Java courses.

  1. 1. Instant Visual Feedback

    Wrong diagonal formulas show up immediately as a broken or shifted X.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Drop the middle column, swap symbols, or change column width with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-condition grid first; then try the X-only cross in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

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

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    Compact if: System.out.print(i==j||j==mid||i==cols+1-j ? "*" : "0"); inside the inner loop.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

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

Common Pitfalls

Mistakes that commonly break star cross patterns.

  1. 1. System.out.println() Inside the Inner Loop

    Each character lands on its own line — you get a column, not a grid row.

    → Use System.out.print for each cell; System.out.println() only after the inner loop finishes.

  2. 2. Wrong Anti-Diagonal Formula

    Using i + j == cols instead of i == cols + 1 - j shifts the secondary diagonal.

    → Keep i == cols + 1 - j for cols=9 (e.g. row 2, col 8 → 2==2).

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every row onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw InputMismatchException.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Forgetting mid

    Computing mid after the loops or using even cols without adjusting center logic.

    → Set mid = cols / 2 + 1 once before the loops; prefer odd column counts.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is one row of nine characters following the same three checks.

rows = 0

Empty pattern

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

Negative

rows < 0

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

Large n

Many rows

Output grows as rows*cols cell visits plus spaces — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.

X-only

Drop middle column

Remove j == mid for a plain X — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change column width

  • Try cols = 7 or cols = 11 and observe mid
  • Keep the same three checks

2. Number cross

  • Replace * with 1 and keep 0 as fill
  • Same nested-loop structure

3. X-only variant

  • Remove j == mid like Example 3
  • Compare output side by side

4. Next in series

  • Continue with Program 46 concentric square
  • Read rows and cols from input

Notes

  • Cell count. Total characters printed = rows×cols (e.g. 4×9 = 36).
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 prints one cross row.
  • Use odd cols so mid points to one clear center column; even widths split the center.

Quick Takeaway: compute mid, loop rows and columns, three-part if for *, else 0, then break the row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows×cols)O(1)
X-only cross (Example 3)O(rows×cols)O(1)
Wrap Up

🎉 Conclusion

The star cross pattern with 0s combines nested loops with a simple grid fill pattern — a natural step after number diamonds. Master the fixed-rows version first, then try user input and the X-only cross in Example 3.

Practice the three examples above, then continue to Program 46 for the concentric number square pattern.

Every cell uses print — keep println() only after the inner column loop finishes.

💡 Best Practices

✅ Do

  • Explain main diagonal, anti-diagonal, and mid column before coding
  • Use print("*") or print("0") and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(rows×cols) time when asked about complexity

❌ Don’t

  • Call System.out.println() inside the inner column loop
  • Forget mid = cols / 2 + 1 before the loops
  • Use i + j == cols instead of i == cols + 1 - j
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this star cross pattern with 0s

Print the pattern the beginner-friendly way.

5
Core concepts
02

Cross check

Three-part if

Code
03

Anti-diagonal

i==cols+1-j

Logic
n 04

Grid size

rows×cols

I/O
O 05

Complexity

O(rows×cols)

Analysis

❓ Frequently Asked Questions

It draws an X (both diagonals) and a vertical middle line using *. All other positions are filled with 0.
Because the pattern uses 9 columns, and mid = cols/2 + 1 = 5. For an odd column count, there is a single center column.
For cols=9, the anti-diagonal satisfies i == cols+1-j (equivalently i == 10-j).
On row i=4, the diagonals hit columns 4 and 6, and the middle column is 5 — three adjacent * characters in the center.
Yes. Delete the condition j == mid. Keep only i == j and i == cols+1-j — see Example 3.
It works best with an odd number of columns so there is a single middle column. Even columns change the center behavior.
O(rows*cols) because the nested loops visit each cell once.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

A * prints on the main diagonal (i==j), anti-diagonal (i==cols+1-j), and middle column (j==mid). Every other cell prints 0.

Continue to Program 46

Move on to the concentric number square pattern in the Java 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