Course contentsShow
← C
Lesson 1032 of 1,21914. Data Structures in CFree lesson

A simple modular hash function

A simple modular hash function

What you'll learn: How to use the modulo operator to turn large pieces of data into small, manageable array indexes.

The Library Analogy

Imagine you have a collection of 1,000 books, but only 10 shelves to put them on. To find a book quickly, you need a system to decide which shelf it belongs on. A hash function is that system. It takes an input (like a book's ID number) and spits out a shelf number (an index).

In C, the most common way to do this is using the modulo operator (%). This operator gives you the remainder of a division. For example, 17 % 10 is 7. No matter how big the starting number is, the result of % 10 will always be between 0 and 9.

Coding the Function

In a hash table, we usually store data in an array. The "hash" is simply the index where we store our value. To keep that index within the bounds of our array, we take the data and apply the modulo of the array's size.

Here is how you write a simple modular hash function for integer data:

#include <stdio.h>

#define TABLE_SIZE 10

// This is our hash function
int hash(int key) {
    // We use the absolute value to handle negative numbers
    if (key < 0) key = -key;
    
    // The modulo operator ensures the result is 0 to 9
    return key % TABLE_SIZE;
}

int main() {
    int myData = 54321;
    int index = hash(myData);
    
    printf("The data %d will be stored at index: %d\n", myData, index);
    
    return 0;
}

Why this works

The modular hash function is fast and predictable. If you pass the number 54321 into the function a thousand times, it will return 1 every single time. This consistency is vital; when you want to look up your data later, the hash function tells you exactly where you put it.

However, keep in mind that since we are cramming many possible numbers into a small range of indexes, two different numbers might end up with the same index (like 11 % 10 and 21 % 10). This is called a collision, and while the modular function is a great start, handling those overlaps is the next step in mastering hash tables.

Key takeaway

A modular hash function maps large keys into a fixed array range using the % operator to ensure the index stays within bounds.