# include # include // // Based on program 10.10, Stephen Kochan, Programming in C. // struct entry { char word[15]; char definition[50]; }; int main ( int argc, char *argv[] ); int compareStrings ( const char s1[], const char s2[] ); int lookup ( const struct entry dictionary[], const char search[], const int entries ); int main ( int argc, char *argv[] ) { const struct entry dictionary[100] = { { "aardvark", "a burrowing African mammal" }, { "abyss", "a bottomless pit" }, { "acumen", "mentally sharp, keen" }, { "addle", "to become confused" }, { "aerie", "a high nest" }, { "affix", "to append or attach" }, { "agar", "a jelly made from seaweed" }, { "ahoy", "a nautical call of greeting" }, { "aigrette", "an ornamental cluster of feathers" }, { "ajar", "partially open" } }; char word[81]; int entries = 10; int entry; // // If the user didn't enter a word, ask for it. // if ( argc < 2 ) { printf ( "Enter word: " ); scanf ( "%14s", word ); } // // Otherwise, copy the command line argument into WORD. // else { strcpy ( word, argv[1] ); } entry = lookup ( dictionary, word, entries ); if ( entry != -1 ) { printf ( "The word \"%s\" means %s.\n", word, dictionary[entry].definition ); } else { printf ( "Sorry, the word \"%s\" is not in my dictionary.\n", word ); } return 0; } int compareStrings ( const char s1[], const char s2[] ) { int i = 0, answer; while ( s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0' ) { i = i + 1; } if ( s1[i] < s2[i] ) { answer = -1; } else if ( s1[i] == s2[i] ) { answer = 0; } else { answer = +1; } return answer; } int lookup ( const struct entry dictionary[], const char search[], const int entries ) { int low = 0; int high = entries - 1; int mid; int result; while ( low <= high ) { mid = ( low + high ) / 2; result = compareStrings ( dictionary[mid].word, search ); if ( result == -1 ) { low = mid + 1; } else if ( result == 0 ) { return mid; } else { high = mid - 1; } } return -1; }