Complete X-Shaped Number Pattern in C

What You’ll Learn
How to print a complete X-shaped pattern using two diagonals: one from top-left to bottom-right and another from top-right to bottom-left.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
Output
1 1
2 2
3 3
4 4
5
4 4
3 3
2 2
1 11
Complete C Program
Print the upper half, then mirror it for the lower half. Two inner loops print the two diagonals.
c
#include <stdio.h>
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = 4; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
for (i = 4; i >= 1; i--) {
for (j = 1; j <= 5; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = 4; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
return 0;
}2
Variation — User Input Version
Read the center size (rows) and build the same two-half logic.
c
#include <stdio.h>
int main() {
int i, j, k;
int rows;
printf("Enter the number of rows (center value): ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= rows; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = rows - 1; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
for (i = rows - 1; i >= 1; i--) {
for (j = 1; j <= rows; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = rows - 1; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
return 0;
}12 people found this page helpful
