Java Program to Interchange Matrix Diagonals

Write a Java Program to Interchange Matrix Diagonals with an example. Or write a Java Program to Interchange Diagonals of a two-dimensional array.

In this example, first, we used the If statement to check whether the matrix is square or not. Next, we used for loop to iterate the two-dimensional array. We used the temp variable within the for loop to assign the matrix diagonal items and interchange them with other diagonal elements. Next, we used another for loop to print the final matrix.

public class InterchangeDiagonals {
	
	public static void main(String[] args) {
		
		int i, j, temp;	
		
		int[][] arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
		
		if(arr.length == arr[0].length) {
			for(i = 0; i < arr.length ; i++)
			{
				temp = arr[i][i];
				arr[i][i] = arr[i][arr.length-i-1];
				arr[i][arr.length - i - 1] = temp;
			}
			
			System.out.println("\n Matrix Items after Interchanging Diagonals are :");
			for(i = 0; i < arr.length ; i++)
			{
				for(j = 0; j < arr[0].length; j++)
				{
					System.out.format("%d \t", arr[i][j]);
				}
				System.out.print("\n");
			}
		}
		else 
		{
			System.out.println("\n Matrix you entered is not a Square Matrix");
		}
	}
}
Java Program to Interchange Matrix Diagonals 1

Java Program to Interchange Matrix Diagonals example 2

This Java Interchange Matrix Diagonals code is the same as the above. However, this Java code allows the user to enter the number of rows, columns, and the matrix items. Please refer to C Program to Interchange Diagonals of a Matrix article to understand this code’s analysis in iteration wise.

import java.util.Scanner;

public class InterchangeDiagonals {
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns, temp;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter Interchangeable Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the Interchangeable Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr[i][j] = sc.nextInt();
			}		
		}
		
		if(rows == columns) {
			for(i = 0; i < rows ; i++)
			{
				temp = arr[i][i];
				arr[i][i] = arr[i][rows-i-1];
				arr[i][rows-i-1] = temp;
			}
			System.out.println("\n Matrix Items after Interchanging Diagonals are :");
			for(i = 0; i < rows ; i++)
			{
				for(j = 0; j < columns; j++)
				{
					System.out.format("%d \t", arr[i][j]);
				}
				System.out.print("\n");
			}
		}
		else 
		{
			System.out.println("\n Matrix you entered is not a Square Matrix");
		}
	}
}

Java interchange matrix Diagonals output

 Please Enter Interchangeable Matrix Rows and Columns :  
3 3

 Please Enter the Interchangeable Matrix Items :  
10 20 30
40 50 60
70 80 90

 Matrix Items after Interchanging Diagonals are :
30 	20 	10 	
40 	50 	60 	
90 	80 	70