In this article, we will understand how to interchange the diagonals. The matrix has a row and column arrangement of its elements. A matrix with m rows and n columns can be called as m × n matrix.
Individual entries in the matrix are called element and can be represented by a[i][j] which suggests that the element a is present in the ith row and jth column.
Below is a demonstration of the same −
Suppose our input is −
The matrix is defined as: 4 5 6 1 2 3 7 8 9
The desired output would be −
The matrix after interchanging the elements: 6 5 4 1 2 3 9 8 7
Algorithm
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
Example 1
Here, we bind all the operations together under the ‘main’ function.
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();
}
}
}Output
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
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
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);
}
}Output
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