Write a c program to rotate the matrix by k times in a clockwise direction using the function
ADVERTISEMENTS
Write a c program to rotate the matrix by k times in a clockwise direction using the function. In this program, 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 c program:
// Write a c program to rotate the matrix by k times
// in a clockwise direction using the function
#include <stdio.h>
// It's the matrix's dimensions
#define M 3
#define N 3
// It's the driver function
// to make clockwise rotation
void rotateClockWise(int arru[][M], int k) {
int temp[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
void displayMatrixData(int arru[][M]) {
for (int i = 0; i < N; i++) {
printf("\t");
for (int j = 0; j < M; j++)
printf("%d\t", arru[i][j]);
printf("\n");
}
}
int main() {
int arru[N][M] = {
{ 12, 13, 14 },
{ 25, 26, 27 },
{ 38, 39, 31 }
};
int k = 2;
printf("-----This is the given matrix before rotation-----\n\n");
displayMatrixData(arru);
// It will rotate matrix by k
rotateClockWise(arru, k);
printf("\n\n------This is the given matrix after rotation %d times------\n\n", k);
// It will display rotated matrix
displayMatrixData(arru);
return 0;
}
Output
-----This is the given matrix before rotation-----
12 13 14
25 26 27
38 39 31
------This is the given matrix after rotation 2 times------
13 14 12
26 27 25
39 31 38