Star + Zero X-Pattern in C++

What You’ll Learn
How to print a pattern made of * and 0 where stars appear on:
- The main diagonal (
i == j) - The opposite diagonal (
i == cols + 1 - j) - The center column (
j == mid)
Everything else prints 0, creating an X shape with a vertical center line.
⭐ Pattern Output
For rows = 4 and cols = 9, the pattern looks like this:
*000*000*
0*00*00*0
00*0*0*00
000***000Complete C++ Program
We loop over a grid (4 rows × 9 columns) and decide whether to print * or 0 based on the position.
#include <iostream>
using namespace std;
int main() {
int i, j;
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 9; j++) {
if (i == j || j == 5 || i == 10 - j)
cout << "*";
else
cout << "0";
}
cout << "\n";
}
return 0;
}🧠 How It Works
Think of it as a grid
We visit every position (i, j) in a fixed-size grid.
Main diagonal
When i == j, we are on the main diagonal, so we print *.
Center column
When j == 5, we are in the middle column, so we print *.
Opposite diagonal
When i == 10 - j (since cols+1 = 10), we print * on the other diagonal.
X + center line
Every cell prints exactly one character, so runtime is proportional to the grid size.
Variation — User Input Version
Make the pattern scalable: for rows, use cols = 2*rows + 1 so there is always a center column.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
if (rows <= 0) return 0;
int cols = 2 * rows + 1;
int mid = rows + 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (i == j || j == mid || i == (cols + 1 - j))
cout << "*";
else
cout << "0";
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Use a different fill character (e.g.,
.) instead of0 - Print the full X by also printing the bottom half (mirror rows) if you want a square
- Change
*to digits like1to create a numeric version - Use separate
rowsandcolsfor a rectangular version - Build each line in a string first if you want extra spacing
Avoid
- Hard-coding magic numbers (like 9 or 5) if you want scalability
- Using even column counts when you need a center line
- Printing extra spaces unless you adjust the diagonals
- Skipping input validation when taking
rowsfrom the user
Key Takeaways
Main diagonal: i == j.
Opposite diagonal: i == cols + 1 - j.
Center line: j == mid.
Overall runtime is about O(rows²) when cols = 2*rows+1.
❓ Frequently Asked Questions
* characters.cout << "0" with cout << " ". (The pattern will be less visible, but the star shape remains.)rows. In the scalable version, the width automatically becomes 2*rows+1 so the center line always exists.rows × (2*rows+1) cells.Explore More C++ Number Patterns!
Once you can detect diagonals and middle lines, you can create many grid-based designs.
The opposite diagonal test i == cols + 1 - j is a standard trick in matrix problems (it mirrors positions across the center).
12 people found this page helpful
