Programming in C

(Barry) #1

226 Chapter 10 Character Strings


int entries = 10;
char word[15];
int entry;
int lookup (const struct entry dictionary[], const char search[],
const int entries);

printf ("Enter word: ");
scanf ("%14s", word);

entry = lookup (dictionary, word, entries);

if ( entry != -1 )
printf ("%s\n", dictionary[entry].definition);
else
printf ("Sorry, the word %s is not in my dictionary.\n", word);

return 0;
}

Program 10.10 Output
Enter word: aigrette
an ornamental cluster of feathers

Program 10.10 Output (Rerun)
Enter word: acerb
Sorry, that word is not in my dictionary.

The compareStringsfunction is identical to the equalStringsfunction up through
the end of the whileloop.When the whileloop is exited, the function analyzes the two
characters that resulted in the termination of the whileloop. If s1[i]is less than s2[i],
s1must be lexicographically less than s2. In such a case, –1 is returned. If s1[i]is equal
to s2[i], the two strings are equal so 0 is returned. If neither is true,s1must be lexico-
graphically greater than s2,in which case 1 is returned.
The lookupfunction defines intvariables lowand highand assigns them initial val-
ues defined by the binary search algorithm.The whileloop executes as long as lowdoes
not exceed high. Inside the loop, the value midis calculated by adding lowand highand
dividing the result by 2.The compareStringsfunction is then called with the word
contained in dictionary[mid]and the word you are searching for as arguments.The
returned value is assigned to the variable result.

Program 10.10 Continued
Free download pdf