Hi ,

i want to use hash tables in my project.
i got few codes in that i got some function called hash()

int hash(char *s)
           {
                  int h =0;
                  for (; *s;s++)
                    h = *s + h * 31;
                    return h % 101;
            }

i understand the process of hash tables but i dont understand
how below statements

h = *s + h * 31;
                              return h % 101;

give a value that will not exceed the array size as choosen(101).
is there any relation between those two statements.

i dont seem the need of using all code here.
though if you want i can provide.

Thanks,
Danian

>[how does it] give a value that will not exceed the array size as choosen(101).
It's done in the return statement with modular arithmetic. That's not my preferred method though, I prefer to return just a basic hash and let the caller fit the range. However, when you say h % 101, that expression guarantees the result to be within the range of [0, 101), provided h isn't negative.

The loop itself is for calculating a hash based on your key. It's the first step of converting a non-index key to an index, ideally ensuring that the index is unique. The second step is fitting that index to the actual range of your hash table.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.