/* Programmer: Greg Perkins Program: rotate.c Class: CS 73 / UNIX Due: April 7, 1998 This program uses pointers to rotate the elements of an array in a positive/right direction or in a negative/left direction. It also uses command line arguments during compilation to adjust the array between 'integer', 'character', or 'float' types. */ #include #ifdef integer #define message printf("'Compiled for an integer array.'\n") #define rcout printf(" %d ", *(a + j)) #define arr_type int #define array {1,2,3,4,5} #define length 5 #define type_name_string "int" #endif #ifdef character #define message printf("'Compiled for a character array.'\n") #define rcout printf(" %c ", *(a + j)) #define arr_type char #define array {'f','l','y','s','w','a','t','t','e','r'} #define length 10 #define type_name_string "char" #endif #ifdef decimal #define message printf("'Compiled for a float array.'\n") #define rcout printf(" %f ", *(a + j)) #define arr_type float #define array {1.11111,2.22222,3.33333,4.44444,5.55555} #define length 5 #define type_name_string "float" #endif /************************** FUNCTION PROTOTYPES ****************************/ rotate(arr_type *arr, int arr_len, int rotation); main() { int direction; int j; arr_type *a; arr_type vec[] = array; a = vec; message; /* verification of type program compiled for */ do { printf("\nEnter the number of spaces to rotate the array elements:\n"); printf("(Positive - right, Negative - left, 0 to stop)\n"); scanf("%d", &direction); if (direction != 0) { printf("\nShift %d place(s) or %d place(s):\n",direction,direction%length); printf("Orig. array : "); for (j = 0; j < length; j++) rcout; printf("\n"); rotate(a, length, direction); printf("Rotated array: "); for (j = 0; j < length; j++) rcout; printf("\n"); } } while (direction != 0); } /************************* FUNCTION DEFINITIONS *****************************/ rotate(arr_type *arr, int arr_len, int rotation) { int j, k; int actual_rotation = rotation % arr_len; arr_type temp; if (actual_rotation < 0) /* negative or left rotation */ { actual_rotation *= -1; for (k = 0; k < actual_rotation; k++) for (j = 0, temp = *(arr + j); j < arr_len; j++) if (j + 1 == arr_len) *(arr + j) = temp; else *(arr + j) = *(arr + j + 1); } else /* positive or right rotation */ for (k = 0; k < actual_rotation; k++) for (j = arr_len - 1, temp = *(arr + j); j >= 0; j--) if (j == 0) *(arr + j) = temp; else *(arr + j) = *(arr + (j - 1)); }