✏️ Explanatory Question
Write a Java program that prints the diagonal elements of a square 2D array.
Given the following array:
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Write a Java program that prints the diagonal elements of a square 2D array.
Given the following array:
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.print("Diagonal Elements: ");
for (int i = 0; i < matrix.length; i++) {
System.out.print(matrix[i][i] + " ");
}
}
}