Finding the diagonal elements of a matrix
Here’s a Java program that finds the diagonal elements of a matrix:
import java.util.Scanner; public class DiagonalElements { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows in the matrix: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns in the matrix: "); int columns = scanner.nextInt(); int[][] matrix = new int[rows][columns]; System.out.println("Enter the elements of the matrix:"); // Read matrix elements from the user for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix[i][j] = scanner.nextInt(); } } System.out.println("Diagonal elements of the matrix:"); // Print diagonal elements for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (i == j) { System.out.print(matrix[i][j] + " "); } } } scanner.close(); } }
In this program, we first prompt the user to enter the number of rows and columns for the matrix. Then we create a 2D array called `matrix` with the specified dimensions. Next, we ask the user to input the elements of the matrix.
After that, we iterate through the matrix and check if the current element’s row index `i` is equal to its column index `j`. If they are equal, it means we are on the diagonal, so we print the element. This is done using the nested `for` loops.
Finally, we close the scanner to release the associated resources.
You can run this program and enter the matrix elements to find the diagonal elements.
No comments yet! You be the first to comment.