交换对角线元素的 Java 程序
在本文中,我们了解如何交换对角线元素。矩阵是其元素的行、列排列。具有 m 行和 n 列的矩阵称为 m × n 矩阵。
矩阵中的各个条目称为元素,可以用 a[i][j] 表示,这表明元素 a 位于第 i 行和第 j 列。
以下是对该元素的说明 −
假设我们的输入是 −
The matrix is defined as: 4 5 6 1 2 3 7 8 9
期望的输出为 −
The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7
算法
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix, and two integer value namely matrix_size and temp. Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using multiple for-loops and swap the required elements of the matrix using a temporary variable. Step 5 - Display the result Step 5 - Stop
范例 1
我们在这里将所有操作都绑定在“main”函数下。
public class InterchangeDiagonals { public static int matrix_size = 3; public static void main (String[] args) { int input_matrix[][] = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; System.out.println("The matrix is defined as: "); for (int i = 0; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } for (int i = 0; i < matrix_size; ++i) if (i != matrix_size / 2) { int temp = input_matrix[i][i]; input_matrix[i][i] = input_matrix[i][matrix_size - i - 1]; input_matrix[i][matrix_size - i - 1] = temp; } System.out.println("\nThe matrix after interchanging the elements: "); for (int i = 0; i < matrix_size; ++i) { for (int j = 0; j < matrix_size; ++j) System.out.print(input_matrix[i][j]+" "); System.out.println(); } } }
输出
The matrix is defined as: 4 5 6 1 2 3 7 8 9 The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7
范例 2
我们在这里将操作封装到函数中,展示面向对象编程。
public class InterchangeDiagonals { public static int matrix_size = 3; static void interchange_diagonals(int input_matrix[][]) { for (int i = 0; i < matrix_size; ++i) if (i != matrix_size / 2) { int temp = input_matrix[i][i]; input_matrix[i][i] = input_matrix[i][matrix_size - i - 1]; input_matrix[i][matrix_size - i - 1] = temp; } System.out.println("\nThe matrix after interchanging the elements: "); for (int i = 0; i < matrix_size; ++i) { for (int j = 0; j < matrix_size; ++j) System.out.print(input_matrix[i][j]+" "); System.out.println(); } } public static void main (String[] args) { int input_matrix[][] = { {4, 5, 6}, {1, 2, 3}, {7, 8, 9} }; System.out.println("The matrix is defined as: "); for (int i = 0; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { System.out.print(input_matrix[i][j] + " "); } System.out.println(); } interchange_diagonals(input_matrix); } }
输出
The matrix is defined as: 4 5 6 1 2 3 7 8 9 The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7
广告