C程式交換給定矩陣的對角線元素
問題
我們需要編寫程式碼來交換主對角線元素和副對角線元素。矩陣的大小在執行時給出。
如果矩陣m和n的值不相等,則列印給定矩陣不是方陣。
只有方陣才能交換主對角線元素,並能與副對角線元素交換。
解決方案
編寫C程式交換給定矩陣的對角線元素的解決方案如下:
交換對角線元素的邏輯如下所示:
for (i=0;i<m;++i){
a = ma[i][i];
ma[i][i] = ma[i][m-i-1];
ma[i][m-i-1] = a;
}示例
以下是交換給定矩陣的對角線元素的C程式:
#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
");
}輸出
執行上述程式時,會產生以下結果:
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP