Lookup Tables in C: A Beginner's Guide

Hello, aspiring programmers! Today, we're going to dive into the exciting world of lookup tables in C. Don't worry if you're new to programming – I'll guide you through this concept step-by-step, just as I've done for countless students over my years of teaching. So, let's embark on this journey together!

C - Lookup Tables

What are Lookup Tables?

Before we jump into examples, let's understand what lookup tables are. Imagine you're in a library, and instead of searching through every book to find what you need, you use a catalog that tells you exactly where each book is located. That's essentially what a lookup table does in programming – it's a data structure that replaces runtime computations with a simpler array indexing operation.

Now, let's explore this concept through some practical examples.

Example 1: Days of the Week

Let's start with a simple example – a lookup table for days of the week.

#include <stdio.h>

int main() {
    const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    int day_number;

    printf("Enter a day number (0-6): ");
    scanf("%d", &day_number);

    if (day_number >= 0 && day_number <= 6) {
        printf("The day is: %s\n", days[day_number]);
    } else {
        printf("Invalid day number!\n");
    }

    return 0;
}

In this example, we've created an array days that stores the names of the week. When a user enters a number between 0 and 6, we can quickly retrieve the corresponding day name using array indexing. This is much faster and cleaner than using a series of if-else statements!

Example 2: Morse Code Translator

Now, let's try something a bit more complex – a Morse code translator.

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

int main() {
    const char *morse[] = {
        ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
        ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
        "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
    };
    char text[100];
    int i;

    printf("Enter a word in uppercase: ");
    scanf("%s", text);

    for (i = 0; i < strlen(text); i++) {
        if (isalpha(text[i])) {
            printf("%s ", morse[text[i] - 'A']);
        }
    }
    printf("\n");

    return 0;
}

Here, we've created a lookup table for Morse code. Each letter's Morse code is stored in the morse array. When a user enters a word, we translate each letter to its Morse code equivalent by using the ASCII value of the letter as an index into our lookup table.

Example 3: Temperature Conversion

Let's create a lookup table for quick Fahrenheit to Celsius conversion.

#include <stdio.h>

#define TABLE_SIZE 101

int main() {
    float celsius_table[TABLE_SIZE];
    int i;

    // Populate the lookup table
    for (i = 0; i < TABLE_SIZE; i++) {
        celsius_table[i] = (i - 32) * 5.0 / 9.0;
    }

    int fahrenheit;
    printf("Enter temperature in Fahrenheit (0-100): ");
    scanf("%d", &fahrenheit);

    if (fahrenheit >= 0 && fahrenheit <= 100) {
        printf("%.2f°C\n", celsius_table[fahrenheit]);
    } else {
        printf("Temperature out of range!\n");
    }

    return 0;
}

In this example, we pre-calculate Celsius values for Fahrenheit temperatures from 0 to 100 and store them in a lookup table. This allows for instant temperature conversions without the need for runtime calculations.

Example 4: Trigonometric Functions

Lookup tables are particularly useful for computationally expensive operations like trigonometric functions. Here's an example of a sine lookup table:

#include <stdio.h>
#include <math.h>

#define TABLE_SIZE 360
#define PI 3.14159265

int main() {
    float sine_table[TABLE_SIZE];
    int i;

    // Populate the lookup table
    for (i = 0; i < TABLE_SIZE; i++) {
        sine_table[i] = sin(i * PI / 180);
    }

    int angle;
    printf("Enter an angle in degrees (0-359): ");
    scanf("%d", &angle);

    if (angle >= 0 && angle < 360) {
        printf("sin(%d°) = %.4f\n", angle, sine_table[angle]);
    } else {
        printf("Angle out of range!\n");
    }

    return 0;
}

This example pre-calculates sine values for angles from 0 to 359 degrees. Using this lookup table, we can quickly retrieve sine values without performing the computationally expensive sine function at runtime.

Lookup Tables in 7-Segment LED Display

Finally, let's look at how lookup tables can be used in a practical application – driving a 7-segment LED display.

#include <stdio.h>

#define SEGMENTS 7

int main() {
    // Lookup table for 7-segment display (0-9)
    const unsigned char seven_seg_digits[10][SEGMENTS] = {
        {1, 1, 1, 1, 1, 1, 0},  // 0
        {0, 1, 1, 0, 0, 0, 0},  // 1
        {1, 1, 0, 1, 1, 0, 1},  // 2
        {1, 1, 1, 1, 0, 0, 1},  // 3
        {0, 1, 1, 0, 0, 1, 1},  // 4
        {1, 0, 1, 1, 0, 1, 1},  // 5
        {1, 0, 1, 1, 1, 1, 1},  // 6
        {1, 1, 1, 0, 0, 0, 0},  // 7
        {1, 1, 1, 1, 1, 1, 1},  // 8
        {1, 1, 1, 1, 0, 1, 1}   // 9
    };

    int digit;
    printf("Enter a digit (0-9): ");
    scanf("%d", &digit);

    if (digit >= 0 && digit <= 9) {
        printf("7-segment display for %d:\n", digit);
        for (int i = 0; i < SEGMENTS; i++) {
            printf("%c ", seven_seg_digits[digit][i] ? '*' : ' ');
        }
        printf("\n");
    } else {
        printf("Invalid digit!\n");
    }

    return 0;
}

In this example, we use a 2D lookup table to store the segment patterns for digits 0-9 on a 7-segment display. Each row represents a digit, and each column represents a segment (1 for on, 0 for off). This allows us to quickly retrieve the correct pattern for any digit.

Conclusion

Lookup tables are a powerful tool in a programmer's arsenal. They can significantly improve performance by trading memory for speed, especially in situations where computations are complex or frequently repeated. As you continue your programming journey, you'll find many more applications for lookup tables.

Remember, practice makes perfect! Try creating your own lookup tables for different scenarios. Happy coding, and don't hesitate to reach out if you have any questions!

Method Description Example
Array Indexing Use an array to store pre-computed values Days of the week, Morse code
Multi-dimensional Arrays Use 2D or 3D arrays for more complex data 7-segment LED display
Pre-calculation Calculate values in advance and store in table Temperature conversion, Trigonometric functions
Character Mapping Map characters to values using ASCII Morse code translator
Range Checking Ensure input is within valid range for table All examples (0-6, 0-100, 0-359, 0-9)

Credits: Image by storyset