Java 计算矩阵每行每列之和的程序

17 Mar 2025 | 阅读 2 分钟

在此程序中,我们需要计算给定矩阵中每行和每列元素的总和。

Java Program to find the sum of each row and each column of a matrix

上图显示了矩阵每行每列元素的总和。

算法

  • 步骤 1: 开始
  • 步骤 2:定义 rows、cols、sumRow、sumCol
  • 步骤 3:初始化矩阵 a[][] ={{1, 2, 3},{4, 5, 6}, {7, 8, 9}}
  • 步骤 4:rows = a.length
  • 步骤 5:cols = a[0].length
  • 步骤 6:重复步骤 7 到步骤 10,直到 i<rows
            //for(i=0; i<rows; i++)
  • 步骤 7:设置 sumRow =0
  • 步骤 8:重复步骤 9,直到 j<cols
  • 步骤 9:sumRow = sumRow + a[i][j]
  • 步骤 10:打印 i+1, sumRow
  • 步骤 11:重复步骤 12 到步骤 15,直到 i<cols
            //for(i=0; i<cols; i++)
  • 步骤 12:设置 sumCol =0
  • 步骤 13:重复步骤 14,直到 j<rows
            //for(j=0; j<rows; j++)
  • 步骤 14:sumCol =sumCol + a[j][i]
  • 步骤 15:打印 i+1, sumCol
  • 步骤 16:结束

程序

输出

Sum of 1 row: 6
Sum of 2 row: 15
Sum of 3 row: 24
Sum of 1 column: 12
Sum of 2 column: 15
Sum of 3 column: 18
下一个主题Java 程序