Complete X-Shaped Number Pattern in C

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

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       1
1

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;
}

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