Star & Zero X Pattern in C#

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Conditions + Nested Loops

What You’ll Learn

How to print an X pattern using * (on diagonals and center column) and 0 elsewhere.

This is a good exercise for learning how to combine multiple conditions inside nested loops.

⭐ Pattern Output

The pattern looks like this:

Output
*000*000*
0*00*00*0
00*0*0*00
000***000
1

Complete C# Program

Print * when the cell is on a diagonal (i == j or i == 10 - j) or on the center column (j == 5). Otherwise print 0.

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

1

Loop through rows and columns

The outer loop prints 4 rows, and the inner loop prints 9 columns per row.

Grid
2

Check diagonal positions

i == j gives the left diagonal and i == 10 - j gives the right diagonal.

Diagonals
3

Add the center column

j == 5 prints the middle vertical line.

Center
4

Fill the rest with 0

If none of the conditions match, the program prints 0.

Fill
2

Variation — Parameterized Width

Generalize the idea by using cols for width and computing the middle column and mirror diagonal dynamically.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 4;
            int 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();
            }
        }
    }
}

Key Takeaways

1

Multiple conditions can combine diagonals + center line.

2

i == j and i == (cols+1)-j are the two diagonals.

3

The center column is \((cols+1)/2\) for odd widths.

4

The rest of the grid is filled with a default character (0 here).

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