Created
July 15, 2014 17:24
-
-
Save bhatiaabhinav/e924e6720bbd07bc2fc0 to your computer and use it in GitHub Desktop.
Demonstrates how to rotate a sqaure 2D array by 90 degrees clockwise. Uses concept of geometric transformation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void rotateRight90(int* sourceArray, int* destArray, int side) | |
{ | |
int srcY, srcX, destY, destX, elem; | |
for (srcY = 1; srcY <= side; srcY++) | |
{ | |
for (srcX = 1; srcX <= side; srcX++) | |
{ | |
elem = sourceArray[(srcY - 1) * side + srcX - 1]; | |
destX = 1 + side - srcY; | |
destY = srcX; | |
destArray[(destY - 1) * side + destX - 1] = elem; | |
} | |
} | |
} | |
void printSquareArray(int* array, int side) | |
{ | |
int r, c; | |
for (r = 0; r < side; r++) | |
{ | |
for (c = 0; c < side; c++) | |
{ | |
printf("%2d ", array[r * side + c]); | |
} | |
printf("\n"); | |
} | |
} | |
int main() | |
{ | |
int sourceArray[25] = | |
{1, 2, 3, 4, 5, | |
6, 7, 8, 9, 10, | |
11, 12, 13, 14, 15, | |
16, 17, 18, 19, 20, | |
21, 22, 23, 24, 25}; | |
int destArray[25]; | |
rotateRight90(sourceArray, destArray, 5); | |
printf("Source array:\n\n"); | |
printSquareArray(sourceArray, 5); | |
printf("\n\n\nRotated right by 90 degrees:\n\n"); | |
printSquareArray(destArray, 5); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment