The Wayback Machine - https://web.archive.org/web/20240927175636/https://www.geeksforgeeks.org/java-program-to-compute-the-sum-of-diagonals-of-a-matrix/
Open In App

Java Program to Compute the Sum of Diagonals of a Matrix

Last Updated : 18 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal and Secondary diagonals. For example, analyze the following 4 × 4 input matrix.

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

Example:

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

 

Intuition:

1. The principal diagonal is constituted by the elements a00, a11, a22, a33, and the row-column condition for the principal diagonal is: row = column

2. However, the secondary diagonal is constituted by the elements a03, a12, a21, a30, and the row-column condition for the Secondary diagonal is: row + column = N – 1

Naive approach: Use two nested loop to iterate over 2D matrix and check for the above condition for principal diagonal and secondary diagonal.

Below is the implementation of the above approach.

Java




// Java Program to Find the Sum of Diagonals of a Matrix
 
// Importing input output classes
import java.io.*;
 
// Main Class
public class GFG {
   
    // To calculate Sum of Diagonals
    static void Sum_of_Diagonals1(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 loop for 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);
    }
 
   
    // 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
        Sum_of_Diagonals1(b, 4);
       
    }
}


Output

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

Time complexity: O(N2)
Auxiliary space: O(1)

Efficient approach: The idea to find the sum of values of principal diagonal is to iterate to N and use the value of matrix[row][row] for the summation of principal diagonal and to find the sum of values of secondary diagonal is to use the value of matrix[row][N – (row + 1)] for summation.

Below is the implementation of the above approach.

Java




// Java Program to Find the Sum of Diagonals of a Matrix
 
// Importing input output classes
import java.io.*;
 
// Main Class
public class GFG {
   
    // 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;
        for(int i=0; i<N; i++)
        {
              // Since for primary diagonal sum the value of
            // row and column are equal
              Pd += matrix[i][i];
           
            // For secondary diagonal sum values of i'th index
            // and j'th index sum is equal to n-1 at each
            // stage of matrix
              Sd += matrix[i][N-(i+1)];
        }
         
       
        // 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);
    }
 
   
    // 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
        Sum_of_Diagonals(b, 4);
    }
}


Output

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

Time complexity: O(N)
Auxiliary space: O(1)



Previous Article
Next Article

Similar Reads

Java Program to Efficiently compute sums of diagonals of a matrix
Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. A00 A01 A02 A03 A10 A11 A12 A13 A20 A21 A22 A23 A30 A31 A32 A33 The primary diagonal is formed by the elements A00, A11, A22, A33. Condition for Principal Diagonal: The row-column condition is row = column
3 min read
Java Program to Accept a Matrix of Order M x N & Interchange the Diagonals
Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix. Steps: 1. We can only interchange diagonals for a square matrix. 2. Create a square matrix of size [M × M]. 3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program.
4 min read
Java Program to Interchange Diagonals of Matrix
Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 14, 1
2 min read
Java Program to Find difference between sums of two diagonals
Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.Examples: Input : mat[][] = 11 2 4 4 5 6 10 8 -12 Output : 15 Sum of primary diagonal = 11 + 5 + (-12) = 4. Sum of primary diagonal = 4 + 5 + 10 = 19. Difference = |19 - 4| = 15. Input : mat[][] = 10 2 4 5 Output : 7 Recommended: Please solve
3 min read
Find smallest and largest element from square matrix diagonals
Given a square matrix of order n*n, find the smallest and largest elements from both diagonals of the given matrix. Examples: Input : matrix = { {1, 2, 3, 4, -10}, {5, 6, 7, 8, 6}, {1, 2, 11, 3, 4}, {5, 6, 70, 5, 8}, {4, 9, 7, 1, 5}}; Output : Principal Diagonal Smallest Element: 1 Principal Diagonal Greatest Element :11 Secondary Diagonal Smallest
15+ min read
Return an array of anti-diagonals of given N*N square matrix
Given a square matrix of size N*N, return an array of its anti-diagonals. For better understanding let us look at the image given below: Examples: Input : Output : 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Approach 1:To solve the problem mentioned above we have two major observations. The first one is, some diagonals start from the zeroth row for each
10 min read
Java Program to Compute the Sum of Numbers in a List Using Recursion
ArrayList is a part of the Collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. Illustration: Input : [1, 3, 9] Output : 13 Here th
5 min read
Java Program to Compute the Sum of Numbers in a List Using For-Loop
Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List. Example: Input : List = [1, 2, 3] Output: Sum = 6 Input : List = [5, 1,
2 min read
Java Program to Compute the Sum of Numbers in a List Using While-Loop
The task is to compute the sum of numbers in a list using while loop. The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Approach Create a list.Create two in
2 min read
Java Program to Compute the Area of a Triangle Using Determinants
In order to compute the area of the triangle, two parameters are needed namely base and height. For this simply the variables are assigned with zeros. The area of the triangle can be computed by using the same third-grade mathematics formula. Area = 1/2(Base * Height) Illustration: Input: (1,3) (5,-2) (-3,6) Output: Area of triangle: 4 Processing:
3 min read
Java Program to Compute GCD
GCD (Greatest Common Divisor) of two given numbers A and B is the highest number that can divide both A and B completely, i.e., leaving remainder 0 in each case. GCD is also called HCF(Highest Common Factor). There are various approaches to find the GCD of two given numbers. Approaches: The GCD of the given two numbers A and B can be calculated usi
5 min read
Java Program to Compute the Running Total of a List
A List is an ordered sequence of elements stored together to form a collection. A list is a structure to perform both positional access and index-based retrieval of the elements. Lists can be used to store duplicate as well as null elements. Running Total of a sequence of the elements is the summation of the previous sum of the elements and the cur
4 min read
Java Program to Implement Steepest Descent Method and Compute Local Optima
The steepest descent method is an optimization algorithm that can be used to find the local minimum of a differentiable function. It is an iterative method that starts with an initial guess for the solution, and then repeatedly takes steps in the direction of the steepest descent (the direction of the greatest negative slope) until it reaches a loc
5 min read
Java Program to Implement Conjugate Method and Compute Local Optima
Problem statement: Given an initial point x_0 and a function f(x), we want to find the local optima of the function using the conjugate method.The conjugate method is an optimization technique that can be used to find the local optima of a function. It is an iterative method that uses the gradient of the function at each iteration to find the direc
5 min read
How to Compute a Discrete-Fourier Transform Coefficients Directly in Java?
The Discrete Fourier Transform (DFT) generally varies from 0 to 360. There are basically N-sample DFT, where N is the number of samples. It ranges from n=0 to N-1. We can get the co-efficient by getting the cosine term which is the real part and the sine term which is the imaginary part. The formula of DFT: Example : Input: Enter the values of simp
4 min read
HashMap compute() method in Java with Examples
The compute(Key, BiFunction) method of HashMap class allows you to update a value in HashMap. The compute() method tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to automatically update a value for given key in HashMap. If the remapping function pa
4 min read
HashTable compute() method in Java with Examples
The compute(Key, BiFunction) method of Hashtable class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). If the remapping function passed in compute() of Hashtable returns null as a return value then the mapping is removed from Hashtable(or remains absent if initially a
3 min read
ConcurrentHashMap compute() method in Java with Examples
The compute(Key, BiFunction) method of ConcurrentHashMap class is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to atomically update a value for given key in ConcurrentHashMap.If the remapping function throws an exception, the exception is re-throw
3 min read
Properties compute(Key, BiFunction) method in Java with Examples
The compute(Key, BiFunction) method of Properties class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). If the remapping function passed in compute() of Properties returns null as a return value then the mapping is removed from Properties(or remains absent if initiall
2 min read
Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Java Program to Maximize sum of diagonal of a matrix by rotating all rows or all columns
Given a square matrix, mat[][] of dimensions N * N, the task is find the maximum sum of diagonal elements possible from the given matrix by rotating either all the rows or all the columns of the matrix by a positive integer. Examples: Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }Output: 6 Explanation: Rotating all the columns of matrix
3 min read
Java Program to Generate a matrix having sum of secondary diagonal equal to a perfect square
Given an integer N, the task is to generate a matrix of dimensions N x N using positive integers from the range [1, N] such that the sum of the secondary diagonal is a perfect square. Examples: Input: N = 3Output:1 2 32 3 13 2 1Explanation:The sum of secondary diagonal = 3 + 3 + 3 = 9(= 32). Input: N = 7Output:1 2 3 4 5 6 72 3 4 5 6 7 13 4 5 6 7 1
3 min read
Java Program for Maximum sum rectangle in a 2D matrix | DP-27
Write a Java program for a given 2D array, the task is to find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29. This problem is mainly an extension of the Largest Sum Contiguous Subarray for 1D array. Recommended: Please solve it on “P
5 min read
Compute modulus division by a power-of-2-number using Wrapper Class
Prerequisite : Compute modulus division by a power-of-2-number Now as you know for getting n modulus 2k, we just need to return k bits(from LSB) in binary representation of n. In Java, you can use Wrapper class toBinaryString() method to get binary string representation of a number and getting substring from (str.length()-k) to end. And then by usi
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 Java Code // Java program to print a // square matrix in Z form import java.lang.*
2 min read
Java Program to Interchange Any Two Rows in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4},
2 min read
Java Program to Find the Frequency of Odd & Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Find Transpose of Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Find Transpose of a Matrix in Java There are two shapes in Matrix to find transpose as mentioned below: Square MatrixRectangle Matrix1. Transpose of Square Matrix The below program fin
4 min read
Article Tags :
Practice Tags :