Rotate Matrix 90 Degrees Clockwise in C++ using Function
ADVERTISEMENTS
Rotate matrix 90 degrees clockwise in c++ using function. In this article, you will learn how to rotate matrix 90 degrees clockwise in c++ using function.
Matrix before Rotation
x1 y1 z1
x2 y2 z2
x3 y3 z3
Matrix after 90 degrees Clockwise Rotation
x3 x2 x1
y3 y2 y1
z3 z2 z1
Source Code
// 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
-----The input matrix before 90 degrees clock-wise rotation-----
43 23 67 41
15 16 17 18
19 10 11 21
23 24 25 26
-----The matrix after 90 degrees clock-wise rotation-----
23 19 15 43
24 10 16 23
25 11 17 67
26 21 18 41