Range Over Built in C

#include <stdio.h>

int main() {
    // Here we use a loop to sum the numbers in an array.
    int nums[] = {2, 3, 4};
    int sum = 0;
    for (int i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
        sum += nums[i];
    }
    printf("sum: %d\n", sum);

    // We can also use the index in the loop when we need it.
    for (int i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
        if (nums[i] == 3) {
            printf("index: %d\n", i);
        }
    }

    // In C, we can use a structure to represent key-value pairs.
    struct KeyValue {
        char* key;
        char* value;
    };

    struct KeyValue kvs[] = {
        {"a", "apple"},
        {"b", "banana"}
    };

    // Iterate over the key-value pairs.
    for (int i = 0; i < sizeof(kvs) / sizeof(kvs[0]); i++) {
        printf("%s -> %s\n", kvs[i].key, kvs[i].value);
    }

    // Iterate over just the keys.
    for (int i = 0; i < sizeof(kvs) / sizeof(kvs[0]); i++) {
        printf("key: %s\n", kvs[i].key);
    }

    // In C, strings are just arrays of characters.
    // We can iterate over each character in a string.
    char* str = "go";
    for (int i = 0; str[i] != '\0'; i++) {
        printf("%d %d\n", i, str[i]);
    }

    return 0;
}

This C program demonstrates iteration over various data structures, similar to the original example. Here’s an explanation of the code:

  1. We start by summing numbers in an array using a standard for loop. In C, we need to manually calculate the length of the array.

  2. We then demonstrate using the index in a loop to find a specific element.

  3. To represent key-value pairs (which are natively supported in some languages), we use a simple structure in C.

  4. We iterate over these key-value pairs, printing both keys and values, and then just the keys.

  5. Finally, we iterate over a string, which in C is represented as an array of characters. We print both the index and the ASCII value of each character.

To compile and run this program:

$ gcc range_example.c -o range_example
$ ./range_example
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

This example showcases how to iterate over different types of data in C, which is conceptually similar to using range in some other languages, although the syntax and exact mechanisms differ.