Cross Pattern with * and 0 in C

What You’ll Learn
How to print a cross/X pattern using * and 0 in C. We’ll use nested loops to scan each row/column and a simple if condition to decide whether to print * or 0.
⭐ 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 (Fixed Size)
We print * on the two diagonals and the center column; everything else is 0.
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 4; i++) {
for (j = 1; j <= 9; j++) {
if (j == i || j == 5 || j == 10 - i)
printf("*");
else
printf("0");
}
printf("\n");
}
return 0;
}🧠 How It Works
Loop through rows
The outer loop for (i = 1; i <= 4; i++) prints each row.
Loop through columns
The inner loop for (j = 1; j <= 9; j++) visits each column in the row.
Decide what to print
We print * when the cell is on a diagonal or on the center column:
j == i, j == 5, or j == 10 - i.
Print zeros elsewhere
If none of those conditions match, we print 0 to fill the background.
Cross/X pattern
This pattern is a great exercise for combining nested loops with multi-condition checks.
Variation — User Input Version
Make it scalable by reading rows and cols and computing the center column dynamically.
#include <stdio.h>
int main() {
int i, j;
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= cols; j++) {
if (j == i || j == (cols + 1) / 2 || j == cols + 1 - i)
printf("*");
else
printf("0");
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Replace
*and0with custom characters (e.g.,Xand.) - Use user input and enforce odd
colsfor a clear center column - Make thicker lines by printing
*whenabs(j - i) <= 1(and similarly for the other diagonal)
Avoid
- Using an even
colsvalue if you want a single clear center column - Forgetting
printf("\n")after each row - Mixing up the right diagonal formula (it should mirror the left)
Key Takeaways
Nested loops let you visit every cell in a grid (row by row, column by column).
The cross is formed by combining three conditions in one if.
For a general version, compute the center column as (cols + 1) / 2.
Time complexity is proportional to the grid size: O(rows * cols).
❓ Frequently Asked Questions
j == i (left) and j == cols + 1 - i (right).(cols + 1) / 2.printf("0") with printf(" ") for a hollow background.Explore More C Number Patterns!
Keep practicing nested loops and conditions with new patterns.
When cols is odd, the center column is exactly (cols + 1) / 2. This makes patterns with a vertical middle line easier to generalize.
12 people found this page helpful
