unsigned long hash(const char* key, int table_size)
unsigned long hash_value = 0;
int prime = 31;
while (*key)
hash_value = (hash_value * prime) + (*key);
key++;
return hash_value % table_size;
Key 1 inserted.
Key 2 inserted.
Key 11 inserted (Collision handled).
Key 21 inserted (Collision handled).
Key 5 inserted.
To make the dictionary work with any data type, replace int value with void *value and store the size or use a union.
Our implementation will consist of four critical components: c program to implement dictionary using hashing algorithms
Let’s build each component step by step. Resizing: not implemented here (fixed capacity)
void put(HashTable *dict, const char *key, int value)
unsigned long index = hash(key, dict->size);
// Check if key already exists
Entry *curr = dict->buckets[index];
while (curr)
if (strcmp(curr->key, key) == 0)
curr->value = value; // Update existing key
return;
curr = curr->next;
// Create new entry
Entry *new_entry = (Entry*)malloc(sizeof(Entry));
new_entry->key = strdup(key); // Allocate and copy string
new_entry->value = value;
new_entry->next = dict->buckets[index];
dict->buckets[index] = new_entry;
dict->count++;