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 <bits/stdc++.h>
using namespace std;
// 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++) {
cout << "\t";
for (int j = 0; j < M; j++)
cout << arru[i][j] << "\t";
cout << endl;
}
}
int main() {
int arru[N][M] = {
{ 22, 23, 24 },
{ 35, 36, 37 },
{ 48, 49, 41 }
};
int k = 2;
cout << "-----This is the given matrix before rotation-----\n\n";
displayMatrixData(arru);
// It will rotate matrix by k
rotateClockWise(arru, k);
cout << "\n\n------This is the given matrix after rotation " << k << " times------\n\n";
// It will display rotated matrix
displayMatrixData(arru);
return 0;
}
Output
-----This is the given matrix before rotation-----
22 23 24
35 36 37
48 49 41
------This is the given matrix after rotation 2 times------
23 24 22
36 37 35
49 41 48