📜  计算矩阵对角线和的Java程序

📅  最后修改于: 2022-05-13 01:54:42.127000             🧑  作者: Mango

计算矩阵对角线和的Java程序

对于给定的二维方阵,任务是找到主对角线和次对角线中元素的总和。例如,分析下面的 4 × 4 输入矩阵。

a00 a01 a02 a03
a10 a11 a12 a13
a20 a21 a22 a23
a30 a31 a32 a33

方法:

1 、主对角线由元素a00、a11、a22、a33构成,主对角线的行列条件为

row = column

2.但是,次对角线由元素a03、a12、a21、a30构成,次对角线的行列条件为

row = number_of_rows – column -1

插图:



Input 1 :  6 7 3 4
           8 9 2 1
           1 2 9 6
           6 5 7 2

Output 1 : Principal Diagonal: 26
           Secondary Diagonal: 14
 
Input 2 : 2 2 2
          1 1 1
          3 3 3

Output 2 :  Principal Diagonal: 6
            Secondary Diagonal: 6

例子:

Java
// Java Program to Find the Sum of Diagonals of a Matrix
  
// Importing input output classes
import java.io.*;
  
// Main Class
public class GFG {
  
    // Method 1
    // To calculate Sum of Diagonals
    static void Sum_of_Diagonals(int[][] matrix, int N)
    {
  
        // Declaring and initializing two variables to zero
        // initially for primary and secondary diagonal
        // count
        int Pd = 0, Sd = 0;
  
        // Two Nested for loops for iteration over a matrix
  
        // Outer loop for rows
        for (int k = 0; k < N; k++) {
  
            // Inner loo pfo columns
            for (int l = 0; l < N; l++) {
  
                // Condition for the principal
                // diagonal
                if (k == l)
                    Pd += matrix[k][l];
  
                // Condition for the secondary diagonal
                if ((k + l) == (N - 1))
                    Sd += matrix[k][l];
            }
        }
  
        // Print and display the sum of primary diagonal
        System.out.println("Sum of Principal Diagonal:"
                           + Pd);
        // Print and display the sum of secondary diagonal
        System.out.println("Sum of Secondary Diagonal:"
                           + Sd);
    }
  
    // Method 2
    // Main driver method
    static public void main(String[] args)
    {
  
        // Input integer array
        // Custom entries in an array
        int[][] b = { { 8, 2, 13, 4 },
                      { 9, 16, 17, 8 },
                      { 1, 22, 3, 14 },
                      { 15, 6, 17, 8 } };
  
        // Passing the array as an argument to the function
        // defined above(Method1-to compute sum of
        // diagonals)
        Sum_of_Diagonals(b, 4);
    }
}


输出
Sum of Principal Diagonal:35
Sum of Secondary Diagonal:58