ArticleZip > Example Of Array Map In C

Example Of Array Map In C

Array Map is a useful function in the C programming language that helps simplify the process of iterating over each element of an array, applying a particular operation, and storing the results in a new array. This powerful function can make your code more concise, readable, and efficient. In this article, we will explore a practical example of how to use Array Map in C.

Let's say we have an array of integers that we want to square. Normally, you would need to write a loop to iterate over each element of the array, square the value, and store it in a new array. However, with Array Map, the process becomes much more straightforward.

First, you define a function that specifies the operation you want to perform on each element of the array. In this case, our function will square the input value. Here is an example of the square function in C:

C

int square(int x) {
    return x * x;
}

Next, you use the Array Map function to apply this square function to each element of the input array and store the results in a new array. Here is the code snippet that demonstrates how to do this:

C

#include 

int square(int x) {
    return x * x;
}

void map(int *input, int *output, int size, int (*func)(int)) {
    for (int i = 0; i < size; i++) {
        output[i] = func(input[i]);
    }
}

int main() {
    int input[] = {1, 2, 3, 4, 5};
    int output[5];

    map(input, output, 5, square);

    for (int i = 0; i < 5; i++) {
        printf("%d ", output[i]);
    }

    return 0;
}

In this code snippet, we first define the square function that squares the input value. Then, we implement the map function, which takes the input array, output array, size of the array, and the function pointer to the operation we want to apply. Inside the map function, we iterate over each element of the input array, apply the specified function using the function pointer, and store the result in the output array.

In the main function, we create an input array with values {1, 2, 3, 4, 5}, an output array to store the squared values, and then call the map function with the square function as the operation to be performed.

When you run this code, the output will be: 1 4 9 16 25. Each element of the input array has been squared, and the results are stored in the output array.

Using Array Map in C can greatly simplify your code, reduce redundancy, and make it more maintainable. By defining reusable functions and applying them to arrays using the map function, you can streamline your coding process and improve the readability of your code. Experiment with different functions and array operations to see the power and flexibility of Array Map in C.