# Thread: Help - how do i define a structure?

1. ## Help - how do i define a structure?

I am trying to define a structure called "wordcount" which has 2 fields: a character array of length 64 called "word" and an integer called "count". How could I do this?

Also, how would I declare an array of 1000 wordcounts called "wordlist"?

Thank you!

2. Code:
```struct wordcount
{
int count;
char word[64];
} wordlist[1000];```
-Prelude

3. ## need help with word count

Thanks, I am trying to write a function that reads a file of words and populates the array "wordlist" with the words in the file, and the count of how many times each occurs.
I then have to use this function in a program that prints out the words from the file with the counts.

e.g. if the file contains "round and round and round we go"
output is:
round 3
and 2
we 1
go 1

I have no idea how to this!

4. The best way would be a binary tree. Read a word, if that word is not in the tree already then insert it. If the word already exists in the tree then increment a counter at that node. You can then traverse the tree and print the word, then the count at each node. A node would look like this:
Code:
```struct node
{
char word[SIZE];
int count;
struct node *left;
struct node *right;
};```
-Prelude

5. Thanks, I am trying to do it without using a binary tree (thats the next question!). I have some code which i think does a similar job to the program I am trying to create but reads the characters from getch not an input file, and counts keywords:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXWORD 100

int getword(char *, int);
int binsearch(char *, struct key *, int);

/*count keywords */
main()
{
int n;
char word [MAXWORD];

while (getword(word, MAXWORD) !=EOF)
if (isalpha(word[0]))
if ((n=binsearch(word, keytab, NKEYS)) >= 0)
keytab[n].count++;
for (n=0; n< NKEYS; n++)
if (keytab[n].count, keytab[n].word);
return 0;
}

/* binsearch: find word in tab[0]...tab[n-1] */
int binsearch(char *word, struct key tab[], int n)
{
int cond;
int low, high, mid;

low = 0;
high = n -1;
while (low <= high) {
mid = (low=high) / 2;
if ((cond = strcmp(word, tab[mid].word)) < 0)
high = mid - 1;
else if (cond > 0)
low = mid + 1;
else
return mid;
}
return -1;

/*getword: get next word or character from input */
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w=word;

while (isspace(c = getch()))
;
if (c != EOF)
*w++=c;
if (!isalpha(c)) {
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
}

This program counts the occurences of C keywords. How could I modify it so it reads a file of words (lower case letters) and populates the array "wordlist" with the words in the file, and the count of how many times each occurs?