C 语言程序求矩阵主对角线和副对角线元素的和


2022 年 3 月 1 日, 学习 eTutorial
2426

什么是矩阵的对角线和非对角线?

矩阵的主对角线:在方阵中,从左上角通过中心元素连接到最右下角的元素称为该矩阵的主对角线。

矩阵的副对角线:在方阵中,从右上角通过中心元素连接到最左下角的元素称为该矩阵的副对角线。

diagonal and off diagonal of a matrix

示例:如果 A 是矩阵

[5 2
2 3]

  • 矩阵 A 的主对角线和为 5 + 3 = 8
  • 矩阵 A 的副对角线和为 2 + 2 = 4

如何使用 C 语言程序计算矩阵主对角线和副对角线之和?

在这个 C 语言程序中,我们接受一个矩阵并使用 for 循环打印出输入的矩阵,现在我们打开一个 for 循环,在该 for 循环内部,我们将主对角线的元素加到一个名为 sum 的变量中。同时,我们还会将副对角线的元素之和加到变量 'a' 中。

matrix elements and positions

最后,我们显示两个和的结果。

注意:只有当行和列相等时才能执行此操作。因此,首先我们使用 if 条件进行检查。如果行和列不匹配,则显示错误消息。

算法

步骤1:包含头文件以使用C语言程序中的内置函数。

步骤 2:声明变量 i, j, m, n, a, sum,并将 a=0, sum=0

步骤 3:将矩阵的阶数读取到变量 m n 中。

步骤 4:检查 m=n,然后执行步骤 5。否则执行步骤 10。

步骤 5:使用嵌套 for 循环将矩阵系数读取到 ma[i][j] 中。

步骤 6:使用 printf 函数显示给定矩阵的每个元素 ma[i][j]

步骤 7:使用 for 循环计算矩阵的和为 sum=sum+ma[i][i],a=a+ma[i][m-i-1]

步骤 8:显示主对角线元素的和为 Sum

步骤 9:显示副对角线元素的和为 a

步骤 10:如果矩阵的阶数不相等,则显示该阶数不是方阵。


此矩阵程序使用以下 C 语言编程主题,请参考这些主题以更好地理解

C 语言源代码

                                          #include <stdio.h>

void main() {
  static int ma[10][10];
  int i, j, m, n, a = 0, sum = 0;
  printf("Enter the order of the matrix \n"); /* accepting the matrix order */
  scanf("%d %d", & m, & n);
  if (m == n) {
    printf("Enter the coefficient s of the matrix\n"); /* enters the elements 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 \n"); /* prints the matrix as such */
    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) {
      sum = sum + ma[i][i]; /*calculating the sum of main diagonal and off diagonal separately*/
      a = a + ma[i][m - i - 1];
    }
    printf("\n The sum of the main diagonal elements is = %d\n", sum);
    printf("The sum of the anti-diagonal elements is   = %d\n", a);
  } else
    printf("The given order is not square matrix\n"); /*cannot calculate for a non square matrix*/
} /* End of main() */
                                      

输出

Enter the order of the matrix
3*3

Enter the coefficients 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

The sum of the main diagonal elements is = 15
The sum of the anti-diagonal elements is   = 15

Run 2

Enter the order of the matrix
2 3

The given order is not square matrix