C program to interchange the diagonal elements in given matrix

In C programming, interchanging the diagonal elements of a matrix involves swapping the main diagonal elements with the secondary (anti) diagonal elements. This operation is only possible with square matrices where the number of rows equals the number of columns.

Syntax

/* Logic to interchange diagonal elements */
for (i = 0; i < n; i++) {
    temp = matrix[i][i];                /* Store main diagonal element */
    matrix[i][i] = matrix[i][n-i-1];    /* Assign secondary diagonal to main */
    matrix[i][n-i-1] = temp;            /* Assign main diagonal to secondary */
}

How It Works

The algorithm works by iterating through each row and swapping elements at positions:

  • Main diagonal: Elements at position [i][i]
  • Secondary diagonal: Elements at position [i][n-i-1]
3x3 Matrix Diagonal Interchange Before 1 2 3 4 5 6 7 8 9 After 3 2 1 4 5 6 9 8 7 Main Diagonal Secondary Diagonal

Example

Following is the C program to interchange the diagonal elements in a given matrix −

#include <stdio.h>

int main() {
    int i, j, m, n, temp;
    int matrix[10][10];
    
    printf("Enter the order of the matrix (m x n): ");
    scanf("%d %d", &m, &n);
    
    if (m != n) {
        printf("The given order is not a square matrix!
"); return 0; } printf("Enter the elements of the matrix:
"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &matrix[i][j]); } } printf("Original matrix:
"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%4d", matrix[i][j]); } printf("
"); } /* Interchange diagonal elements */ for (i = 0; i < m; i++) { temp = matrix[i][i]; matrix[i][i] = matrix[i][m-i-1]; matrix[i][m-i-1] = temp; } printf("Matrix after interchanging diagonals:
"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%4d", matrix[i][j]); } printf("
"); } return 0; }
Enter the order of the matrix (m x n): 3 3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
Original matrix:
   1   2   3
   4   5   6
   7   8   9
Matrix after interchanging diagonals:
   3   2   1
   4   5   6
   9   8   7

Key Points

  • Only square matrices (m = n) can have diagonal elements interchanged
  • Main diagonal elements are at positions [i][i]
  • Secondary diagonal elements are at positions [i][n-i-1]
  • The center element in odd-dimension matrices remains unchanged

Conclusion

Interchanging diagonal elements in C involves swapping main diagonal with secondary diagonal elements using a simple loop. The operation requires a square matrix and uses temporary variable for safe element swapping.

Updated on: 2026-03-15T14:16:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements