Grupo
Arrays y Vectores en C++
Ojetivo
1. Define dos arrays del mismo tamaño.
2. Implementa una función que itere sobre ambos arrays y sume sus elementos correspondientes.
3. Almacena el resultado en un nuevo array.
4. Genera el nuevo array con los elementos sumados.
5. Prueba el programa con diferentes arrays para asegurar su correcto funcionamiento.
Desarrolla una función que sume dos arrays elemento por elemento.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
Summed array: 6 6 6 6 6
Comparte este ejercicio C++