Sum Two Arrays Element by Element in C++
In this exercise, you will implement a function that sums two arrays element by element. This means that for two given arrays of the same size, the function will return a new array where each element is the sum of the corresponding elements in the original arrays.
This practice focuses on element-wise operations, a fundamental concept in data processing, computer graphics, and mathematical computing.
Logic Components
1. Parallel Iteration
We use a single loop index i to access the same position in three different arrays simultaneously.
2. Element-wise Addition
The operation C[i] = A[i] + B[i] ensures that only values at the matching indices are combined.
3. Buffer Storage
A result array is pre-allocated to store the outputs, preserving the original data in the input arrays.
Educational Note:
In more advanced C++ or scientific computing (like with libraries like Eigen or Armadillo), this operation is often vectorized, allowing the CPU to process multiple additions in a single clock cycle.
Learning Objectives
- 1. Manage multiple arrays within a single loop.
- 2. Practice function parameters involving arrays and pointers.
- 3. Understand the importance of consistent array sizes for linear operations.
- 4. Learn to output processed data from a result buffer.
Solution Implementation
#include <iostream>
using namespace std;
// Function to sum two arrays element by element
void sumArrays(int arr1[], int arr2[], int result[], int size) {
// Loop through each element of the arrays
for (int i = 0; i < size; i++) {
result[i] = arr1[i] + arr2[i]; // Add corresponding elements
}
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {5, 4, 3, 2, 1};
int size = sizeof(arr1) / sizeof(arr1[0]);
int result[size]; // Result array
sumArrays(arr1, arr2, result, size);
cout << "Summed array: ";
for (int i = 0; i < size; i++) {
cout << result[i] << " ";
}
cout << endl;
return 0;
}