#include #include #include #define LENGTH 1000 #define MAXLINE 32 #define SCREEN_WIDTH 80 void promptString(const char * prompt, char * response); void readWords(char words[][MAXLINE], int * numWords); void selectionSort(char words[][MAXLINE], int numWords); void swap(char * str1, char * str2); int longestWord(const char words[][MAXLINE], int numWords); int wordsPerLine(int width); void printWords(const char words[][MAXLINE], int numWords); void printOne(const char * word, int width); int main() { int numWords; char words[LENGTH][MAXLINE]; //an automatic array of strings, this is not the norm readWords(words, & numWords); printWords(words, numWords); selectionSort(words, numWords); printWords(words, numWords); return 0; } void readWords(char words[][MAXLINE], int * numWords) //precondition: input is open and ready to read; words is completely allocated { *numWords = 0; printf("Enter a word [EOF to quit]: "); while(scanf("%s", words[*numWords]) == 1) { ++*numWords; printf("Enter a word [EOF to quit]: "); } } void selectionSort(char words[][MAXLINE], int numWords) { int i, j, min; for(i = 0; i < numWords - 1; i++) { min = i; for(j = i + 1; j < numWords; j++) { if(strcmp(words[j], words[min]) < 0) min = j; } if(min != i) swap(words[i], words[min]); } } void swap(char * str1, char * str2) //precondition: str1 and str2 are not NULL and have enough memory allocated { char temp[MAXLINE]; strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); } int longestWord(const char words[][MAXLINE], int numWords) //returns index of longest string found in words, returns -1 if words is empty { if(numWords == 0) return -1; else { int k; int max = 0; for(k = 0; k < numWords; k++) if(strlen(words[k]) > strlen(words[max])) max = k; return max; } } int wordsPerLine(int width) //assuming 80 char lines in display, return number of words that could fit { return SCREEN_WIDTH/width; } void printWords(const char words[][MAXLINE], int numWords) //output words left to right, formatted to width of { int k; int maxLen = strlen(words[longestWord(words, numWords)]); int lineCount = wordsPerLine(maxLen + 1); //space between each word for(k = 0; k < numWords; k++) { printOne(words[k], maxLen); if(lineCount != 0 && (k+1) % lineCount == 0) printf("\n"); } printf("\n"); } void printOne(const char * word, int width) //output word left justified in width wide character spaces { int numSpaces = width - strlen(word) + 1; int k; printf("%s", word); for(k = 0; k < numSpaces; k++) printf(" "); }