Skip to content

Commit 45023b7

Browse files
committed
linear search dictionary lookup
1 parent d0fefda commit 45023b7

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

prog.10.9.c

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Program to use the dictionary lookup program
2+
3+
#include <stdio.h>
4+
#include <stdbool.h>
5+
6+
struct entry
7+
{
8+
char word[15];
9+
char definition[50];
10+
};
11+
12+
bool equalStrings (const char s1[], const char s2[])
13+
{
14+
int i = 0;
15+
bool areEqual;
16+
17+
while ( s1[i] == s2[i] &&
18+
s1[i] != '\0' && s2[i] != '\0' )
19+
++i;
20+
21+
if ( s1[i] == '\0' && s2[i] == '\0' )
22+
areEqual = true;
23+
else
24+
areEqual = false;
25+
26+
return areEqual;
27+
}
28+
29+
// function to look up a word inside a dictionary
30+
31+
int lookup (const struct entry dictionary[], const char search[],
32+
const int entries)
33+
{
34+
int i;
35+
bool equalStrings (const char s1[], const char s2[]);
36+
37+
for ( i = 0; i < entries; ++i )
38+
if ( equalStrings (search, dictionary[i].word) )
39+
return i;
40+
41+
return -1;
42+
}
43+
44+
int main (void)
45+
{
46+
const struct entry dictionary[100] =
47+
{
48+
{ "aardvark", "a burrowing African mammal" },
49+
{ "abyss", "a bottomless pit" },
50+
{ "acumen", "mentally sharp; keen" },
51+
{ "addle", "to become confused" },
52+
{ "aerie", "a high nest" },
53+
{ "affix", "to append; attach" },
54+
{ "agar", "a jelly made from seaweed" },
55+
{ "ahoy", "a nautical call of greeting" },
56+
{ "aigrette", "an ornamental cluster of feathers" },
57+
{ "ajar", "partially opened" }
58+
};
59+
60+
char word[10];
61+
int entries = 10;
62+
int entry;
63+
int lookup (const struct entry dictionary[], const char search[],
64+
const int entries);
65+
66+
printf ("Enter word: ");
67+
scanf ("%14s", word);
68+
entry = lookup (dictionary, word, entries);
69+
70+
if ( entry != -1 )
71+
printf ("%s\n", dictionary[entry].definition);
72+
else
73+
printf ("Sorry, the word %s is not in my dictionary.\n", word);
74+
75+
return 0;
76+
}

0 commit comments

Comments
 (0)