Home > Backend Development > C++ > body text

C program to swap diagonal elements of a given matrix

王林
Release: 2023-08-25 18:02:03
forward
1488 people have browsed it

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;
}
Copy after login

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>");
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template