
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Interchange Diagonal Elements in a Given Matrix using C
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 −
#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
"); scanf ("%dx%d",&m,&n); if (m==n){ printf ("Enter the co-efficients of the matrix
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ scanf ("%d",&ma[i][j]); } } printf ("The given matrix is
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("
"); } 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
"); printf ("Main & secondary diagonal
"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("
"); } } else printf ("The given order is not square matrix
"); }
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
Advertisements