C 程序查找矩阵每行和每列的总和


2022 年 4 月 21 日, Learn eTutorial
1316

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

如何计算矩阵的行和列的总和?

在此 C 程序中,我们需要分别添加矩阵的行和列,这意味着如果我们有一个三行三列的矩阵,我们需要有六个单独的结果。示例:如果我们有一个矩阵 A

2   5 

10  2

那么第一行的总和 = 2 + 5 = 7

第二行的总和 = 10 + 2 = 12

第一列的总和 = 2 + 10 = 12

第二列的总和 = 5 + 2 = 7

因此,在此 C 程序中,我们接受用户输入的矩阵并按原样显示矩阵。现在我们需要声明一个名为 sum 的变量并将其初始化为零。现在我们打开一个嵌套的 for 循环,并在内部 for 循环中递增行元素以分别获得行的总和。

同样,我们为列总和打开下一个 for 循环,并执行与行中相同的操作,但在此过程中,我们递增列而不是行。最后,我们分别显示每个总和。

算法

步骤 1:包含头文件以在 C 程序中使用内置头文件。

步骤 2:声明变量 i, j, m, n, sum=0, m1[][]

步骤 3:将矩阵的阶数读入变量 mn

步骤 4:使用嵌套的 for 循环将矩阵的系数读入数组 m1[i][j]

步骤 5:使用 for 循环计算行和,即 sum=sum+m1[i][j]。并将第 i 行的总和显示为 sum

步骤 6:设置 sum=0 并重复步骤 5 直到 i

步骤 7:使用嵌套的 for 循环计算列 sum,即 sum=sum+m1[i][j] 并显示它。

步骤 1:包含头文件以在 C 程序中使用内置头文件。

步骤 2:声明变量 i, j, m, n, sum=0, m1[][]

步骤 3:将矩阵的阶数读入变量 mn

步骤 4:使用嵌套的 for 循环将矩阵的系数读入数组 m1[i][j]

步骤 5:使用 for 循环计算行和,即 sum=sum+m1[i][j]。并将第 i 行的总和显示为 sum。

 

C 语言源代码

                                          #include <stdio.h>

void main() {
  static int m1[10][10];
  int i, j, m, n, sum = 0;
  printf("Enter the order of the matrix\n"); /* accepting the order of the matrix */
  scanf("%d %d", & m, & n);
  printf("Enter the co-efficient of the matrix\n"); /* enters the elements of matrix */
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
      scanf("%d", & m1[i][j]);
    }
  }
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
      sum = sum + m1[i][j]; /* calculating the row sum separately for each row */
    }
    printf("The Sum of the %d rows is = %d\n", i, sum);
    sum = 0;
  }
  sum = 0;
  for (j = 0; j < n; ++j) {
    for (i = 0; i < m; ++i) {
      sum = sum + m1[i][j]; /* calculating the column sum separately as we done in row */
    }
    printf("The Sum of the %d columns is = %d\n", j, sum);
    sum = 0;
  }
} /*End of main() */
                                      

输出

Enter the order of the matrix
3*3

Enter the co-efficient s of the matrix
1 2 3
4 5 6
7 8 9

The Sum of the 0 rows is = 6

The Sum of the 1 row is = 15

The Sum of the 2 rows is = 24

The Sum of the 0 columns is = 12

The Sum of the 1 column is = 15

The Sum of the 2 columns is = 18