问题我们需要编写代码来交换主对角线元素与次对角线元素。矩阵的大小在运行时给出。
如果矩阵 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 n3x3enter the co-efficient of the matrix123456789the given matrix is1 2 34 5 67 8 9matrix after changing themain & secondary diagonal3 2 14 5 69 8 7run 2:enter the order of the matrix m and n4x3the given order is not square matrix
以上就是给定矩阵的c程序以交换对角线元素的详细内容。