# Write a java program to rotate the matrix by k times in a clockwise direction using the function

Write a __java program__ to rotate the matrix by k times in a clockwise direction using the function. There are you will learn how to rotate the matrix by k times in a clockwise direction using the function.

Take an example to make this clockwise rotation through a __java program__:

```
// Write a java program to rotate the matrix by k times
// in a clockwise direction using the function
import java.util.Scanner;
public class Main {
// It's the matrix's dimensions
public static final int M = 3, N = 3;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[][] arru = {
{
32, 33, 34
}, {
45, 46, 47
}, {
58, 59, 51
}
};
int k = 2;
System.out.println("-----This is the given matrix before rotation-----\n");
displayMatrixData(arru);
// It will rotate matrix by k
rotateClockWise(arru, k);
System.out.println("\n\n------This is the given matrix after rotation " + k + " times------\n");
// It will display rotated matrix
displayMatrixData(arru);
}
// It's the driver function
// to make clockwise rotation
public static void rotateClockWise(int[][] arru, int k) {
int[] temp = new int[M];
k = k % M;
for (int i = 0; i<N; i++) {
for (int t = 0; t<M - k; t++)
temp[t] = arru[i][t];
for (int j = M - k; j<M; j++)
arru[i][j - M + k] = arru[i][j];
for (int j = k; j<M; j++)
arru[i][j] = temp[j - k];
}
}
// This will display the matrix
public static void displayMatrixData(int[][] arru) {
for (int i = 0; i<N; i++) {
System.out.print("\t");
for (int j = 0; j<M; j++)
System.out.print(arru[i][j] + "\t");
System.out.print("\n");
}
}
}
```

**Output:**

`-----This is the given matrix before rotation-----`

` 32 33 34 `

45 46 47

58 59 51

`------This is the given matrix after rotation 2 times------`

` 33 34 32 `

46 47 45

59 51 58

## Tags:

# write a java program to rotate matrix clockwise

# write a java program to rotate matrix anticlockwise

# write a java program to rotate each ring of matrix anticlockwise by k elements