C++ Online Compiler
Example: C++ Program to Rotate a Matrix by K times in a Clockwise direction using Function
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// C++ Program to Rotate a Matrix by K times in a Clockwise direction using 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
Clear
ADVERTISEMENTS