Write a C program to read elements in a matrix and interchange elements of primary(major) diagonal with secondary(minor) diagonal. C program for interchanging diagonals of a matrix. Logic to interchange diagonals of a matrix in C programming.

**Example**

**Input**

Input matrix elements: 1 2 3 4 5 6 7 8 9

**Output**

Matrix after interchanging its diagonal: 3 2 1 4 5 6 9 8 7

## Required knowledge

Basic C programming, For loop, Array

Read more -

## Program to interchange diagonal elements of a matrix

```
/**
* C program to interchange diagonals of a matrix
*/
#include <stdio.h>
#define MAX_ROWS 3
#define MAX_COLS 5
int main()
{
int A[MAX_ROWS][MAX_COLS];
int row, col, size, temp;
/* Input elements in matrix from user */
printf("Enter elements in matrix of size %dx%d: \n", MAX_ROWS, MAX_COLS);
for(row=0; row<MAX_ROWS; row++)
{
for(col=0; col<MAX_COLS; col++)
{
scanf("%d", &A[row][col]);
}
}
size = (MAX_ROWS < MAX_COLS) ? MAX_ROWS : MAX_COLS;
/*
* Interchange diagonal of the matrix
*/
for(row=0; row<size; row++)
{
col = row;
temp = A[row][col];
A[row][col] = A[row][(size-col) - 1];
A[row][(size-col) - 1] = temp;
}
/*
* Print the interchanged diagonals matrix
*/
printf("\nMatrix after diagonals interchanged: \n");
for(row=0; row<MAX_ROWS; row++)
{
for(col=0; col<MAX_COLS; col++)
{
printf("%d ", A[row][col]);
}
printf("\n");
}
return 0;
}
```

Output

Enter elements in matrix of size 3x3: 1 2 3 4 5 6 7 8 9 Matrix after diagonals interchanged: 3 2 1 4 5 6 9 8 7

Happy coding 😉

### Recommended posts

- Array and Matrix programming exercises index.
- C program to find sum of main diagonal elements of a matrix.
- C program to find sum of opposite diagonal elements of a matrix.
- C program to find lower triangular matrix.
- C program to find upper triangular matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.

<pre><code> ----Your Source Code---- </code></pre>