Finding the trace of a matrix
Here’s a Java program that calculates the trace of a square matrix:
import java.util.Scanner; public class MatrixTrace { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows/columns in the square matrix: "); int size = scanner.nextInt(); int[][] matrix = new int[size][size]; System.out.println("Enter the elements of the matrix:"); // Reading matrix elements from the user for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { matrix[i][j] = scanner.nextInt(); } } // Calculating the trace of the matrix int trace = calculateTrace(matrix); System.out.println("The trace of the matrix is: " + trace); } public static int calculateTrace(int[][] matrix) { int trace = 0; int size = matrix.length; // Summing the diagonal elements for (int i = 0; i < size; i++) { trace += matrix[i][i]; } return trace; } }
In this program, we first prompt the user to enter the size of the square matrix. Then, we create a 2D array to store the matrix elements entered by the user.
Next, we calculate the trace of the matrix using the `calculateTrace()` method. The method iterates over the diagonal elements of the matrix and adds them to the `trace` variable.
Finally, we display the trace of the matrix to the user.
No comments yet! You be the first to comment.