Transpose and Rotate Matrix

This program transposes a matrix and then rotates it by 90 degrees.

Problem Statement

Write a Java program to transpose and then rotate a 3x3 matrix by 90 degrees clockwise.

Source Code

1 public class TransposeRotateMatrix {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Transpose and Rotate Matrix");
4 int[][] A = {{1,2,3},{4,5,6},{7,8,9}};
5 // Transpose
6 for(int i=0;i<3;i++){
7 for(int j=i+1;j<3;j++){
8 int temp=A[i][j]; A[i][j]=A[j][i]; A[j][i]=temp;
9 }
10 }
11 // Rotate by reversing rows
12 for(int i=0;i<3;i++){
13 for(int j=0;j<3/2;j++){
14 int temp=A[i][j]; A[i][j]=A[i][3-1-j]; A[i][3-1-j]=temp;
15 }
16 }
17 for(int i=0;i<3;i++){
18 for(int j=0;j<3;j++){
19 System.out.print(A[i][j]+" ");
20 }
21 System.out.println();
22 }
23 }
24 }

Program Output

Eduinq Transpose and Rotate Matrix
7 4 1 
8 5 2 
9 6 3 

Explanation

First transpose swaps elements across diagonal. - Then rows are reversed to achieve rotation. - Together produces 90 degree rotated matrix. Conclusion: Demonstrates transpose followed by rotation of matrix.

Quick Links to Explore