C Online Compiler
Example: Matrix Rotation 90 Degrees Clockwise in C using Function
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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
Clear
ADVERTISEMENTS