Watch java videos
Write a program to rotate a matrix (square matrix N x N) by 90 degrees (clockwise).
import java.io.*;
class RotateMatrix
{
int r;
int Arr[][];
int NewA[][];
void fill_array()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the order of the matrix");
r=Integer.parseInt(br.readLine());
Arr=new int[r][r];
NewA=new int[r][r];
System.out.println("ENTER THE VALUES OF THE ARRAY");
for(int i=0;i<r;i++)
{
for(int j=0;j<r;j++)
{
Arr[i][j]=Integer.parseInt(br.readLine());
}
}
}
void tilt()
{
for(int i=0;i<r;i++)
{
int k=0;
for(int j=(r-1);j>=0;j--)
{
NewA[i][j]=Arr[k][i];
k++;
}
}
}
void display()
{
System.out.println("----------THE ORIGINAL MATRIX---------------");
for(int i=0;i<r;i++)
{
for(int j=0;j<r;j++)
{
System.out.print(Arr[i][j]+"\t");
}
System.out.println();
}
System.out.println("----------THE 90% TILTED MATRIX---------------");
for(int a=0;a<r;a++)
{
for(int b=0;b<r;b++)
{
System.out.print(NewA[a][b]+"\t");
}
System.out.println();
}
}
public static void main()throws IOException
{
RotateMatrix obj=new RotateMatrix();
obj.fill_array();
obj.tilt();
obj.display();
}
}Download free Sample papers
Output:
Enter the order of the matrix
3
ENTER THE VALUES OF THE ARRAY
1
2
3
4
5
6
7
8
9
----------THE ORIGINAL MATRIX---------------
1 2 3
4 5 6
7 8 9
----------THE 90% TILTED MATRIX---------------
7 4 1
8 5 2
9 6 3