ProgrammingNoob
ProgrammingNoob

Reputation: 3

Calculating sum of ascii values of a char

I need to create a hash function that is supposed to return the sum of the ASCII values mod by 100(which is HASH_TABLE_SIZE) in a given char, but I don't seem to be getting the correct output. How do I correct this?

int string_set::hash_function(const char *s) {

int h = 0;
for (int i =0; i < *s; i++)
{
    h = h + int(s[i]);
    return h % HASH_TABLE_SIZE;
}
return h;
}

Upvotes: 0

Views: 3479

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Do not return in the middle of process.

Try this:

int string_set::hash_function(const char *s) {

    int h = 0;
    for (int i =0; s[i] != '\0'; i++) // the loop condition didn't seem good
    {
        // the cast to unsigned char may be needed for system in which the type char is signed
        h = (h + (unsigned char)s[i]) % HASH_TABLE_SIZE;
    }
    return h;
}

This code will work well only if your system use ASCII code as character code for char.

Upvotes: 2

Related Questions