计算矩阵的每行每列的元素总和

1 说明

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

2 算法思路

  • 步骤1:开始
  • 第2步:定义行,列,colR,sumRow,sumCol
  • 步骤3:初始化矩阵a [] [] = {{1,2,3},{4,5,6},{7,8,9}}
  • 步骤4:行= a.length
  • 步骤5: cols = a [0] .length
  • 步骤6:直到i <rows
            // for(i = 0; i <rows; i ++)为止,将步骤7重复到步骤10
  • 步骤7: SET 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: SET sumCol = 0
  • 步骤13:重复步骤14直到j <rows
            // for(j = 0; j <rows; j ++)
  • 步骤14: sumCol = sumCol + a [j] [i]
  • 步骤15:打印i + 1,sumCol
  • 步骤16:结束

3 程序实现

/**
 * 一点教程网: http://www.yiidian.com
 */
public class SumofRowColumn    
{    
    public static void main(String[] args) {    
        int rows, cols, sumRow, sumCol;    
            
        //Initialize matrix a    
        int a[][] = {       
                        {1, 2, 3},    
                        {4, 5, 6},    
                        {7, 8, 9}    
                    };    
              
          //Calculates number of rows and columns present in given matrix    
          rows = a.length;    
        cols = a[0].length;    
            
        //Calculates sum of each row of given matrix    
        for(int i = 0; i < rows; i++){    
            sumRow = 0;    
            for(int j = 0; j < cols; j++){    
              sumRow = sumRow + a[i][j];    
            }    
            System.out.println("Sum of " + (i+1) +" row: " + sumRow);    
        }    
            
        //Calculates sum of each column of given matrix    
        for(int i = 0; i < cols; i++){    
            sumCol = 0;    
            for(int j = 0; j < rows; j++){    
              sumCol = sumCol + a[j][i];    
            }    
            System.out.println("Sum of " + (i+1) +" column: " + sumCol);    
        }    
    }    
}  

以上代码输出结果为:

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

 

热门文章

优秀文章