C Program to display the numbers in X pattern

In C programming, displaying numbers in an X pattern is a common pattern printing exercise. The X pattern consists of numbers arranged such that they appear on the main diagonal (top-left to bottom-right) and anti-diagonal (top-right to bottom-left) of a square grid.

Syntax

for(i = 0; i < rows; i++) {
    for(j = 0; j < rows; j++) {
        if(i == j || i + j == rows - 1) {
            printf("%d", i + 1);
        } else {
            printf(" ");
        }
    }
    printf("<br>");
}

Algorithm

Step 1: Start
Step 2: Declare variables i, j, rows
Step 3: Read number of rows from user
Step 4: Use nested loops where outer loop runs from 0 to rows-1
Step 5: Inner loop also runs from 0 to rows-1
Step 6: If i==j (main diagonal) or i+j==rows-1 (anti-diagonal)
        Print the row number (i+1)
        Else print space
Step 7: Print newline after each row
Step 8: Stop

Example

The following C program demonstrates how to display numbers in X pattern −

#include <stdio.h>

int main() {
    int i, j, rows;
    
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    
    printf("\nX Pattern:<br>");
    for(i = 0; i < rows; i++) {
        for(j = 0; j < rows; j++) {
            if(i == j || i + j == rows - 1) {
                printf("%d", i + 1);
            } else {
                printf(" ");
            }
        }
        printf("<br>");
    }
    
    return 0;
}
Enter number of rows: 5

X Pattern:
1   1
 2 2 
  3  
 4 4 
5   5

How It Works

The program uses two key conditions to create the X pattern:

  • Main Diagonal (i == j): When row index equals column index, numbers are printed on the main diagonal from top-left to bottom-right.
  • Anti-Diagonal (i + j == rows - 1): When the sum of row and column indices equals rows-1, numbers are printed on the anti-diagonal from top-right to bottom-left.
  • Other positions: Spaces are printed to maintain the X structure.

Conclusion

The X pattern program effectively demonstrates nested loops and conditional logic in C. The key is identifying the mathematical relationship between diagonal positions using row and column indices.

Updated on: 2026-03-15T14:07:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements