Grupo
Arrays y Vectores en C++
Ojetivo
1. Define un array con varios valores enteros.
2. Crea una función que recorra el array para calcular la suma de sus elementos.
3. Devuelve la suma total de la función.
4. Imprime la suma de los elementos del array.
5. Asegúrate de que el programa muestre la suma correcta de todos los elementos.
Calcula la suma de los elementos de un array.
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 calculate the sum of array elements
int sumArray(int arr[], int size) {
int sum = 0; // Initialize sum to 0
// Loop through the array to add each element to sum
for (int i = 0; i < size; i++) {
sum += arr[i]; // Add the current element to sum
}
return sum; // Return the total sum
}
// Function to print the elements of the array
void printArray(int arr[], int size) {
// Loop through the array and print each element
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each number followed by a space
}
cout << endl; // Print a newline after the array
}
int main() {
// Define an array of numbers
int numbers[] = {5, 10, 15, 20, 25};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the function to calculate the sum
int totalSum = sumArray(numbers, size);
// Print the sum of the array elements
cout << "The sum of the array elements is: " << totalSum << endl;
return 0; // End of program
}
Salida
The sum of the array elements is: 75
Comparte este ejercicio C++