ปัญหา
เราจำเป็นต้องเขียนโค้ดเพื่อแลกเปลี่ยนองค์ประกอบแนวทแยงหลักกับองค์ประกอบแนวทแยงรอง ขนาดของเมทริกซ์ถูกกำหนดที่รันไทม์
หากขนาดของค่าเมทริกซ์ 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\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");
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
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