Grupo
Funciones en C++
Ojetivo
1. Define una función que tome un array de enteros y su tamaño como argumentos.
2. Inicializa una variable para almacenar el resultado y configúrala en 1 (la identidad de la multiplicación).
3. Usa un bucle para iterar por el array y multiplicar cada elemento por el resultado.
4. Devuelve el producto final de la función.
5. En la función principal, declara e inicializa un array con algunos valores.
6. Llama a la función y muestra el resultado.
Crea una función que calcule el producto de los elementos de un array.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output operations
using namespace std; // Use the standard namespace
// Function to calculate the product of all elements in an array
int productOfArray(int arr[], int size) {
int product = 1; // Initialize the product variable with 1
// Loop through each element in the array
for (int i = 0; i < size; i++) {
product *= arr[i]; // Multiply each element with the current product
}
return product; // Return the final product
}
// Main function - program entry point
int main() {
// Declare and initialize an array with some integers
int numbers[] = {2, 3, 4, 5};
// Calculate the size of the array
int size = sizeof(numbers) / sizeof(numbers[0]);
// Call the function to compute the product of the array elements
int result = productOfArray(numbers, size);
// Print the result to the console
cout << "The product of the array elements is: " << result << endl;
return 0; // End of the program
}
Salida
The product of the array elements is: 120
Comparte este ejercicio C++