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

在本教程中,我们将讨论一个程序,以查找给定矩阵的每一行和每一列的总和。

为此,我们将得到一个说A * B的矩阵。我们的任务是遍历矩阵的所有元素,找到矩阵的每一行和每一列的总和。

示例

#include <iostream>
using namespace std;
#define m 7
#define n 6
//计算每一行的总和
void calc_rsum(int arr[m][n]){
   int i,j,sum = 0;
   for (i = 0; i < 4; ++i) {
      for (j = 0; j < 4; ++j) {
         sum = sum + arr[i][j];
      }
      cout << "Sum of the row "<< i << ": " << sum << endl;
      sum = 0;
   }
}
//计算每列的总和
void calc_csum(int arr[m][n]) {
   int i,j,sum = 0;
   for (i = 0; i < 4; ++i) {
      for (j = 0; j < 4; ++j) {
         sum = sum + arr[j][i];
      }
      cout << "Sum of the column "<< i << ": " << sum <<endl;
      sum = 0;
   }
}
int main() {
   int i,j;
   int arr[m][n];
   int x = 1;
   for (i = 0; i < m; i++)
   for (j = 0; j < n; j++)
   arr[i][j] = x++;
   calc_rsum(arr);
   calc_csum(arr);
   return 0;
}

输出结果

Sum of the row 0: 10
Sum of the row 1: 34
Sum of the row 2: 58
Sum of the row 3: 82
Sum of the column 0: 40
Sum of the column 1: 44
Sum of the column 2: 48
Sum of the column 3: 52