Array Exercises
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.
Required knowledge
Basic C programming, C for loop, ArrayS

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 3
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:
10 20 30
40 50 60
70 80 90
Matrix after diagonals interchanged:
30 20 10
40 50 60
90 80 70
Process returned 0 (0x0) execution time : 16.921 s
Program to interchange diagonal elements of a matrix
/**
* C program to interchange diagonals of a matrix
*/
#include <stdio.h>
int main()
{
int A[10][10];
int row, col, size, temp,m,n;
printf("Enter no rows:");
scanf("%d",&m);
printf("Enter no of columns:");
scanf("%d",&n);
/* Input elements in matrix from user */
printf("Enter elements in matrix of size %dx%d: \n", m, n);
for(row=0; row<m; row++)
{
for(col=0; col<n; col++)
{
scanf("%d", &A[row][col]);
}
}
size = (m < n) ? m : n;
/*
* 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<m; row++)
{
for(col=0; col<n; col++)
{
printf("%d ", A[row][col]);
}
printf("\n");
}
return 0;
}
