Group
Arrays and Vectors in C++
Objective
1. Define two arrays of the same size.
2. Implement a function that iterates through both arrays and adds their corresponding elements.
3. Store the result in a new array.
4. Output the new array containing the summed elements.
5. Test the program with different arrays to ensure it works correctly.
Develop a function that sums two arrays element by element.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// 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 of arr1 and arr2, store in result
}
}
int main() {
// Define two arrays to sum
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {5, 4, 3, 2, 1};
int size = sizeof(arr1) / sizeof(arr1[0]); // Calculate the size of the arrays
int result[size]; // Create an array to store the result
// Call the function to sum the arrays
sumArrays(arr1, arr2, result, size);
// Output the result array
cout << "Summed array: ";
for (int i = 0; i < size; i++) {
cout << result[i] << " "; // Print each element of the summed array
}
cout << endl;
return 0; // End of program
}
Output
Summed array: 6 6 6 6 6