C program to interchange the diagonal elements in given matrix

CServer Side ProgrammingProgramming

Problem

We need to write a code to interchange the main diagonal elements with the secondary diagonal elements. The size of the matrix is given at runtime.

If the size of matrix m and n values are not equal, then it prints that the given matrix is not a square.

Only a square matrix can interchange the main diagonal elements and can interchange with the secondary diagonal elements.

Solution

The solution to write a C program to interchange the diagonal elements in given matrix is as follows −

The logic to interchange the diagonal elements is explained below −

for (i=0;i<m;++i){
   a = ma[i][i];
   ma[i][i] = ma[i][m-i-1];
   ma[i][m-i-1] = a;
}

Example

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

 Live Demo

#include<stdio.h>
main (){
   int i,j,m,n,a;
   static int ma[10][10];
   printf ("Enter the order of the matrix m and n\n");
   scanf ("%dx%d",&m,&n);
   if (m==n){
      printf ("Enter the co-efficients of the matrix\n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            scanf ("%d",&ma[i][j]);
         }
      }
      printf ("The given matrix is \n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("\n");
      }
      for (i=0;i<m;++i){
         a = ma[i][i];
         ma[i][i] = ma[i][m-i-1];
         ma[i][m-i-1] = a;
      }
      printf ("Matrix after changing the \n");
      printf ("Main & secondary diagonal\n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("\n");
      }
   }
   else
      printf ("The given order is not square matrix\n");
}

Output

When the above program is executed, it produces the following result −

Run 1:
Enter the order of the matrix m and n
3x3
Enter the co-efficient of the matrix
1
2
3
4
5
6
7
8
9
The given matrix is
1 2 3
4 5 6
7 8 9
Matrix after changing the
Main & secondary diagonal
3 2 1
4 5 6
9 8 7

Run 2:
Enter the order of the matrix m and n
4x3
The given order is not square matrix
raja
Updated on 01-Sep-2021 13:07:55

Advertisements