Star & Zero X Pattern in C#

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:
*000*000*
0*00*00*0
00*0*0*00
000***000Complete 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.
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
Loop through rows and columns
The outer loop prints 4 rows, and the inner loop prints 9 columns per row.
Check diagonal positions
i == j gives the left diagonal and i == 10 - j gives the right diagonal.
Add the center column
j == 5 prints the middle vertical line.
Fill the rest with 0
If none of the conditions match, the program prints 0.
Variation — Parameterized Width
Generalize the idea by using cols for width and computing the middle column and mirror diagonal dynamically.
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
Multiple conditions can combine diagonals + center line.
i == j and i == (cols+1)-j are the two diagonals.
The center column is \((cols+1)/2\) for odd widths.
The rest of the grid is filled with a default character (0 here).
12 people found this page helpful
