Calculate the sum of diagonals in a matrix

16

Title: Calculate the sum of diagonals in a matrix

In this blog post, we’ll delve into the world of matrices and explore how to calculate the sum of diagonals in a 3×3 matrix using Java. We’ll provide a Java program with detailed comments and explanations, along with examples to illustrate the concept. By the end, you’ll have a clear understanding of how to perform this operation efficiently in Java.

Understanding the 3×3 Matrix

A 3×3 matrix is a fundamental structure in linear algebra, represented as:

In this matrix, we have two main diagonals: the principal diagonal (from the top-left to the bottom-right) and the secondary diagonal (from the top-right to the bottom-left). Our goal is to calculate the sum of elements along these diagonals.

Java Program for Diagonal Sum Calculation

Let’s dive into the Java program that calculates the sum of diagonals in a 3×3 matrix:

Java
public class DiagonalSum3x3Matrix {

public static void main(String[] args) {
// Initialize the 3x3 matrix
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Initialize variables to hold sum of principal and secondary diagonals
int principalSum = 0;
int secondarySum = 0;

// Loop through the rows of the matrix
for (int i = 0; i < matrix.length; i++) {
// Add elements of principal diagonal (from top-left to bottom-right)
principalSum += matrix[i][i];

// Add elements of secondary diagonal (from top-right to bottom-left)
secondarySum += matrix[i][matrix.length - 1 - i];
}

// Display the sums of principal and secondary diagonals
System.out.println("Sum of Principal Diagonal: " + principalSum);
System.out.println("Sum of Secondary Diagonal: " + secondarySum);
}
}

Explanation of the Java Program

• We start by initializing our 3×3 matrix matrix with values from 1 to 9.
• Two variables principalSum and secondarySum are used to store the sums of the principal and secondary diagonals, respectively.
• We then enter a for loop that iterates through each row of the matrix.
• For the principal diagonal, we add the element at the position [i][i] to principalSum.
• For the secondary diagonal, we add the element at the position [i][matrix.length - 1 - i] to secondarySum.

Example Calculation

Let’s consider the following 3×3 matrix:

• Principal Diagonal Sum: ( 1 + 5 + 9 = 15 )
• Secondary Diagonal Sum: ( 3 + 5 + 7 = 15 )

Learn and practice more on Array Programs: Array

Conclusion

In this blog post, we’ve explored how to calculate the sum of diagonals in a 3×3 matrix using Java. The program efficiently computes the sums of the principal and secondary diagonals, demonstrating a fundamental matrix operation.