C++ - Program - Add Two Arrays

#include <iostream>
// Function to add two arrays
void addArrays(int arr1[], int arr2[], int size, int result[]) {
    for (int i = 0; i < size; i++) {
        result[i] = arr1[i] + arr2[i];
    }
}
// Function to display an array
void displayArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}
int main() {
    const int size = 5;
    // Define two arrays
    int arr1[size] = {1, 2, 3, 4, 5};
    int arr2[size] = {6, 7, 8, 9, 10};
    // Define a result array
    int result[size];
    // Add the arrays
    addArrays(arr1, arr2, size, result);
    // Display the arrays
    std::cout << "Array 1: ";
    displayArray(arr1, size);
    std::cout << "Array 2: ";
    displayArray(arr2, size);
    std::cout << "Result Array: ";
    displayArray(result, size);
    return 0;
}

In this program, we define a function addArrays that takes two arrays (arr1 and arr2) of integers, along with the size of the arrays, and adds the corresponding elements together. The result is stored in another array called result. The function uses a loop to iterate over each element of the arrays and performs the addition operation.

The displayArray function is used to display an array to the console. It iterates over each element of the array and prints it.

In the main function, we define two arrays arr1 and arr2 with size 5, and initialize them with values. We also define a result array with the same size to store the result of the addition. We then call the addArrays function to add the arrays and store the result in the result array. Finally, we display all three arrays (input arrays and the resultant array) using the displayArray function.