Java Program to find the Sum of Diagonals of a Matrix
Hey, fellow code crafters! In this tutorial, you are going to learn the Java program to find the Sum of Diagonals of a Matrix.
Find the Sum of Diagonals of a Matrix in Java
The following Java programming inserts the main diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left) of a matrix. It first transmits a 3×3 matrix with example values. It then iterates throughout the matrix in order to determine the sum of elements along the main diagonal using matrix[i][i], where i can range from 0 to 2 (assuming a 3×3 matrix). Similarly, it determines the sum of elements along the secondary diagonal given matrix[i][cols – 1 – i]. The helper method printMatrix() is utilised for printing the results to the console together with the matrix for viewing. This programme effectively demonstrates how to execute matrix iteration and diagonally summation in Java.
public class CodespeedyTechnology { public static void main(String[] args) { int[][] matrix = { {8, 12, 5}, {7, 15, 19}, {45, 46, 72} }; int sumfirstDiagonal = 0; int sumSecondDiagonal = 0; int rows = matrix.length; int cols = matrix[0].length; for (int i = 0; i < rows; i++) { sumfirstDiagonal += matrix[i][i]; } for (int i = 0; i < rows; i++) { sumSecondDiagonal += matrix[i][cols - 1 - i]; } System.out.println("Matrix:"); printMatrix(matrix); System.out.println("Sum of first diagonal: " + sumfirstDiagonal); System.out.println("Sum of second diagonal: " + sumSecondDiagonal); } public static void printMatrix(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + "\t"); } System.out.println(); } } }
Matrix: 8 12 5 7 15 19 45 46 72 Sum of first diagonal: 95 Sum of second diagonal: 65
Leave a Reply