Matrix Rotation 90 Degrees Clockwise in C using Function
ADVERTISEMENTS
Matrix rotation 90 degrees clockwise in C using function. In this article, you will learn how to transform a matrix rotation 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
// Matrix Rotation 90 Degrees Clockwise in C using Function
#include <stdio.h>
#define N 4
void rotate90DegClockwise(int x[N][N]);
void printMatrix(int x[N][N]);
// It's the driver function
int main() {
int arru[N][N] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
printf("-----The input matrix before 90 degrees clock-wise rotation-----\n\n");
printMatrix(arru);
// this function will be rotate each element clock-wise
rotate90DegClockwise(arru);
printf("\n-----The matrix after 90 degrees clock-wise rotation-----\n\n");
printMatrix(arru);
return 0;
}
// This function will 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;
}
}
}
// This function will print the transformed matrix
void printMatrix(int arr[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d\t", arr[i][j]);
printf("\n\n");
}
}
Output
-----The input matrix before 90 degrees clock-wise rotation-----
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
-----The matrix after 90 degrees clock-wise rotation-----
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4