Star & Zero X Pattern in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 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 C# 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 (i = 1; i <= rows; i++) walks each row of the grid.

Inner Loop

j = 1..cols

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

Three Checks

Diagonals + mid

i == j || j == mid || i == cols + 1 - j prints *; else print 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 C# the outer loop runs i = 1..rows, the inner loop runs j = 1..cols, and a three-part condition picks "*" or "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 prints *, else 0, then WriteLine().

📝 Problem & Approach

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

C#
// rows = 4, cols = 9
//*000*000*
//0*00*00*0
//00*0*0*00
//000***000

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows (e.g. 4).
colsintNumber of columns (e.g. 9 — odd width gives a clear center).
midintCenter column: (cols + 1) / 2 (e.g. 5 when cols is 9).
iintOuter loop — current row index (1 to rows).
jintInner loop — current column index (1 to cols).

Minimal workflow

Pseudocode
mid = (cols + 1) / 2
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
Nested loops + condition*000*000* fixed 4×9Learning and interviews
Parameterized rows/colsmid = (cols + 1) / 2Flexible rectangular grids
Diagonals onlyDrop j == mid checkPure X without center line

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Walk columnsfor (j = 1; j <= cols; j++)
Center columnmid = (cols + 1) / 2
Star checkif (i == j || j == mid || i == cols + 1 - j)
Print starConsole.Write("*");
Print fillConsole.Write("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 || 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 C# programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 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.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;

            for (i = 1; i <= 4; i++)
            {
                for (j = 1; j <= 9; j++)
                {
                    if (i == j || j == 5 || i == 10 - j)
                        Console.Write("*");
                    else
                        Console.Write("0");
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

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

📈 Parameterized Grid

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

Example 2 — Variable Rows and Columns

Compute mid and use (cols + 1) - j for the anti-diagonal.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 4, cols = 9;
            int mid = (cols + 1) / 2;

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= cols; j++)
                {
                    if (i == j || j == mid || i == (cols + 1) - j)
                        Console.Write("*");
                    else
                        Console.Write("0");
                }
                Console.WriteLine();
            }
        }
    }
}

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 print stars.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 4; i++)
            {
                for (int j = 1; j <= 9; j++)
                {
                    if (i == j || i == 10 - j)
                        Console.Write("*");
                    else
                        Console.Write("0");
                }
                Console.WriteLine();
            }
        }
    }
}

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

using System; brings in Console. Set loop variables i, j for a 4 × 9 grid.

Setup
2

Nested loops build grid

for (i = 1; i <= rows; i++) and for (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

Print star or zero

Matching cells print "*"; all others print "0".

Output
5

New line

Console.WriteLine() 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 == 10 - 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 Write vs WriteLine without complex math.

Example: put WriteLine 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 TryParse 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 C# 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. Prefer TryParse

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

  3. 3. Keep WriteLine Outside

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Odd Column Width

    Use odd cols so mid = (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 squares per line, you almost certainly put WriteLine inside the print loop.

Common Pitfalls

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

  1. 1. WriteLine Inside the Inner Loop

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

    → Use Write("*") or Write("0") per cell; WriteLine 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 = (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. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse 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 ReadLine

Convert.ToInt32 throws — use TryParse.

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. Print * when i == j || j == mid || i == cols + 1 - j; else print 0.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Prefer odd cols for a clear center column; compute mid = (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 prints *, else 0, then WriteLine().

⏱️ 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 (i = 1; i <= rows; i++) and for (j = 1; j <= cols; j++)
  • Star: if (i == j || j == mid || i == cols + 1 - j)
  • Print "*" on match, "0" elsewhere
  • Compute mid = (cols + 1) / 2 for center column
  • Prefer odd cols for a clear vertical line

❌ Don’t

  • Call WriteLine 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 || 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 == 10 - j because cols + 1 is 10 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 = (cols + 1) / 2, and replace 10 - j with (cols + 1) - j — 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.

Did you Know? 🔊

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

Continue to Program 46

Move on to the next pattern in the C# 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