Grupo
Arrays y Vectores en C++
Ojetivo
1. Define un array con varios valores enteros.
2. Crea una función que tome el array y su tamaño como entrada.
3. Dentro de la función, suma todos los elementos del array.
4. Divide la suma entre el tamaño del array para calcular el promedio.
5. Devuelve el promedio calculado.
6. Prueba el programa con diferentes arrays.
Implementa una función que calcule el promedio 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 average of the elements in the array
double calculateAverage(int arr[], int size) {
double sum = 0; // Initialize a variable to store the sum of the elements
// Loop through the array to sum all the elements
for (int i = 0; i < size; i++) {
sum += arr[i]; // Add each element to the sum
}
return sum / size; // Return the average (sum divided by the number of elements)
}
int main() {
// Define an array of numbers
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the function to calculate the average
double average = calculateAverage(numbers, size);
// Print the result
cout << "The average of the array elements is: " << average << endl;
return 0; // End of program
}
Salida
The average of the array elements is: 30
Comparte este ejercicio C++