C++ Online Compiler
Example: Rotate Matrix 90 Degrees Clockwise in C++ using Function
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Rotate Matrix 90 Degrees Clockwise in C++ using Function #include <iostream> #define N 4 using namespace std; void rotate90DegClockwise(int x[N][N]); void printMatrix(int x[N][N]); int main() { int arru[N][N] = { {43, 23, 67, 41}, {15, 16, 17, 18}, {19, 10, 11, 21}, {23, 24, 25, 26} }; cout << "-----The input matrix before 90 degrees clock-wise rotation-----\n\n"; printMatrix(arru); // this function will be rotate each element clock-wise rotate90DegClockwise(arru); cout << "\n-----The matrix after 90 degrees clock-wise rotation-----\n\n"; printMatrix(arru); return 0; } // It's the function to rotate the matrix 90 degree clock-wise void rotate90DegClockwise(int a[N][N]) { // It will traverse the each cycle for (int i = 0; i < N / 2; i++) { for (int j = i; j < N - i - 1; j++) { // It will swap elements of each cycle in clock-wise direction int temp = a[i][j]; a[i][j] = a[N - 1 - j][i]; a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j]; a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i]; a[j][N - 1 - i] = temp; } } } // It's the function for print the rotated matrix void printMatrix(int arr[N][N]) { for (int i = 0; i < N; i++) { cout << "\t"; for (int j = 0; j < N; j++) cout << arr[i][j] << "\t"; cout << "\n\n"; } }
Output
Clear
ADVERTISEMENTS