Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.
Certainly! Below is a Java program that takes a matrix as input from the user and rotates it 90 degrees clockwise. The program first reads the dimensions of the matrix and then the elements of the matrix. After that, it performs the rotation and prints the rotated matrix.
import java.util.Scanner;
public class RotateMatrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number of rows and columns
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
// Initialize the matrix
int[][] matrix = new int[rows][cols];
// Input the matrix elements
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
// Rotate the matrix 90 degrees clockwise
int[][] rotatedMatrix = rotateMatrix(matrix, rows, cols);
// Print the rotated matrix
System.out.println("Rotated Matrix (90 degrees clockwise):");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(rotatedMatrix[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
public static int[][] rotateMatrix(int[][] matrix, int rows, int cols) {
int[][] rotated = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotated[j][rows - 1 - i] = matrix[i][j];
}
}
return rotated;
}
}
rotateMatrix
method creates a new matrix (rotated
) with dimensions swapped (the number of rows becomes the number of columns and vice versa). It then fills this new matrix with the elements of the original matrix in a rotated position.RotateMatrix.java
.javac RotateMatrix.java
.java RotateMatrix
.