문제
주 대각선 요소를 보조 대각선 요소와 교환하는 코드를 작성해야 합니다. 행렬의 크기는 런타임에 제공됩니다.
행렬 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