Print numbers in matrix diagonal pattern in C Program.

In C programming, we can create a matrix pattern where numbers are filled in diagonal order. This pattern fills elements starting from the top-left corner, moving diagonally down and to the right.

1 2 4 3 5 7 6 8 9 Diagonal Pattern Numbers filled along diagonal lines

Syntax

void printDiagonal(int n);
// n: size of the matrix (n x n)

Algorithm

The approach involves filling the matrix in two phases −

  • Upper Triangle: Fill diagonals starting from the first row
  • Lower Triangle: Fill remaining diagonals starting from the first column

Example

#include <stdio.h>

void printDiagonal(int n) {
    int mat[n][n], i, j, k, d = 1, m;
    
    // Fill upper triangle (including main diagonal)
    for (i = 0; i < n; i++) {
        j = i;
        k = 0;
        for (j = i; j >= 0; j--) {
            mat[k][j] = d;
            d++;
            k++;
        }
    }
    
    // Fill lower triangle
    for (k = 1; k < n; k++) {
        i = m = k;
        for (j = n-1; j >= m; j--) {
            mat[i][j] = d;
            d++;
            i++;
        }
    }
    
    // Print the matrix
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("<br>");
    }
}

int main() {
    int n = 3;
    printf("Matrix of size %d x %d in diagonal pattern:<br>", n, n);
    printDiagonal(n);
    
    printf("\nMatrix of size 4 x 4 in diagonal pattern:<br>");
    n = 4;
    printDiagonal(n);
    
    return 0;
}
Matrix of size 3 x 3 in diagonal pattern:
1 2 4 
3 5 7 
6 8 9 

Matrix of size 4 x 4 in diagonal pattern:
1 2 4 7 
3 5 8 11 
6 9 12 14 
10 13 15 16 

How It Works

The algorithm works by traversing diagonals in a specific order −

  1. First Phase: Start from each element in the first row and move diagonally down-left
  2. Second Phase: Start from each element in the first column (except [0][0]) and move diagonally down-right
  3. Each diagonal is filled with consecutive numbers

Time and Space Complexity

Complexity Value Description
Time O(n²) Each matrix element is visited once
Space O(n²) Storage for the n x n matrix

Conclusion

The diagonal pattern matrix fills numbers sequentially along diagonal lines, creating a unique pattern. This technique is useful for understanding matrix traversal algorithms and 2D array manipulation in C programming.

Updated on: 2026-03-15T11:57:16+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements