Home  >  Article  >  Backend Development  >  C program to swap diagonal elements of a given matrix

C program to swap diagonal elements of a given matrix

王林
王林forward
2023-08-25 18:02:031478browse

C program to swap diagonal elements of a given matrix

Question

We need to write code to swap the main diagonal elements with the sub-diagonal elements. The size of the matrix is ​​given at runtime.

If the sizes of the matrix m and n values ​​are not equal, print that the given matrix is ​​not square.

Only square matrices can interchange main diagonal elements or sub-diagonal elements.

Solution

The solution to write a C program to swap the diagonal elements in a given matrix is ​​as follows-

Swap the diagonal elements The logic 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 for swapping the diagonal elements in a given matrix -

Real-time demonstration

#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</p><p>");
   scanf ("%dx%d",&m,&n);
   if (m==n){
      printf ("Enter the co-efficients of the matrix</p><p>");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            scanf ("%d",&ma[i][j]);
         }
      }
      printf ("The given matrix is </p><p>");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("</p><p>");
      }
      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 </p><p>");
      printf ("Main & secondary diagonal</p><p>");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("</p><p>");
      }
   }
   else
      printf ("The given order is not square matrix</p><p>");
}

Output

When the above program is executed, the following results will be produced-

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

The above is the detailed content of C program to swap diagonal elements of a given matrix. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete