Hi, sorry about that :$
Code:
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# define COLS 5
# define ROWS 5
void shift_right(int a[ROWS][COLS]);/*Right*/
void shift_left(int a[ROWS][COLS]);/*Left*/
void shift_up(int a[ROWS][COLS]);/*Upward*/
void shift_dn(int a[ROWS][COLS]); /*Downward*/
void print_array(int a[ROWS][COLS]); /*Prints*/
int main() {
srand(time(NULL));
char choice;
int i,j,array[ROWS][COLS];
for(i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++)
array[i][j]=1+rand()%100;
}
printf("the 2D array is:\n");
print_array(array);
printf("Please enter the direction of rotatation: ");
scanf("%c",&choice);
printf("the rotated 2D aaray is:\n");
if(choice=='r'){
shift_right(array);
print_array(array);
}
else if(choice=='l'){
shift_left(array);
print_array(array);
}
else if(choice=='u'){
shift_up(array);
print_array(array);
}
else if(choice=='d'){
shift_dn(array);
print_array(array);
}
else
printf("ERROR; %c is not a valid choice\n", choice);
return 0;
}
/* Rotates to the right*/
void shift_right(int a[ROWS][COLS]) {
int i,j,temp[ROWS];
for(i=0;i<ROWS;i++) {
for (j=4;j<COLS;j++)
temp[i]=a[i][j];
}
for(i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++) {
if (j!=COLS-1)
a[i][j]=a[i+1][j];
else
a[i][COLS-5]=temp[i];
}
}
}
/*Rotates to the left*/
void shift_left(int a[ROWS][COLS]) {
int i,j,temp[ROWS];
for(i=0;i<ROWS;i++) {
for (j=0;j<COLS-4;j++)
temp[i]=a[i][j];
}
for (i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++) {
if (j!=COLS-1)
a[i][j]=a[i][j+1];
else
a[i][COLS-1]=temp[i];
}
}
}
/*Rotates upward*/
void shift_up(int a[ROWS][COLS]) {
int i,j,k=0,temp[ROWS];
for(i=0;i<ROWS;i++)
temp[i]=a[ROWS-5][i];
for (i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++) {
if (i!=ROWS-4)
a[i][j]=a[i][j];
else
a[ROWS-1][j]=temp[j];
}
}
}
/* Rotates downward*/
void shift_dn(int a[ROWS][COLS]) {
int i,j,temp[ROWS];
for(i=0;i<ROWS;i++)
temp[i]=a[ROWS-1][i];
for (i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++) {
if (i != ROWS-1)
a[i][j]=a[i][j];
else
a[ROWS-2][j]=temp[j];
}
}
}
/* Prints the array*/
void print_array(int a[ROWS][COLS]) {
int i,j;
for(i=0;i<ROWS;i++) {
for (j=0;j<COLS;j++)
printf("%5d ", a[i][j]);
printf("\n");
}
}
And here's a sample output
Code:
the 2D array is:
13 81 19 89 82
61 25 45 28 46
30 30 67 39 17
39 92 69 69 69
78 64 86 76 60
Please enter the direction of rotatation: l
the rotated 2D aaray is:
81 19 89 82 13
25 45 28 46 61
30 67 39 17 30
92 69 69 69 39
64 86 76 60 78
Press any key to continue . . .
When rotating a 2D array to the right, all the elements in the 1st column moves to the 2nd, all the elements in the 2nd column moves to the 3rd,and all the elements in the last column moves to the 1st
Thank you