Programming Examples
Java program to rotation input matrix 90 degree and print
Write a program to declare a square matrix A[ ][ ] of order MxM where 'M' is the number of rows and the number of columns, such that M must be greater than 2 and  less than 10. Accept the value of M as user input. Display an appropriate message for  an invalid input. Allow the user to input integers  into  this  matrix.  Perform  the  following tasks:
(a) Display the original matrix.
(b) Rotate the matrix 90° clockwise as shown below:
Original matrix
Â
1 2 3
4 5 6
7 8 9
Â
Rotated matrix
7 4 1
8 5 2
9 6 3
Â
(c) Find the sum of the elements of the four comers of the matrix.
Test your program with the sample data and some random data: Example 1
INPUT : M = 3
3 4 9
2 5 8
1 6 7
OUTPUT :
ORIGINAL MATRIX
3 4 9
2 5 8
1 6 7
MATRIX AFTER ROTATION
1 2 3
6 5 4
7 8 9
Sum of the corner elements = 20
Example 2
INPUT : M = 4
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
OUTPUT :
ORIGINAL MATRIX
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
Solution
import java.util.*;
class Rotate90
{
public static void main(String arr[])
{
int matrix[][]=new int[10][10];
int m,a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Value of M : ");
m=sc.nextInt();
System.out.println("Enter "+(m*m)+" Elements for Matrix : ");
for(a=0;a<m;a++)
{
for(b=0;b<m;b++)
{
matrix[a][b]=sc.nextInt();
}
}
System.out.println("Original Matrix :");
for(a=0;a<m;a++)
{
for(b=0;b<m;b++)
{
System.out.print(matrix[a][b]+" ");
}
System.out.println();
}
// Rotate a Matrix anti clock wise 90 degree
for (int x = 0; x < m / 2; x++)
{
for (int y = x; y < m - x - 1; y++)
{
int temp = matrix[x][y];
matrix[x][y] = matrix[y][m - 1 - x];
matrix[y][m - 1 - x]= matrix[m - 1 - x][m - 1 - y];
matrix[m - 1 - x][m - 1 - y] = matrix[m - 1 - y][x];
matrix[m - 1 - y][x] = temp;
}
}
System.out.println("Matrix After Rotate 90 Degree:");
for(a=0;a<m;a++)
{
for(b=0;b<m;b++)
{
System.out.print(matrix[a][b]+" ");
}
System.out.println();
}
}
}
Output