Group
Functions in C++
Objective
1. Define a function that takes an integer array and its size as arguments.
2. Initialize a variable to store the result and set it to 1 (the identity for multiplication).
3. Use a loop to iterate through the array and multiply each element with the result.
4. Return the final product from the function.
5. In the main function, declare and initialize an array with some values.
6. Call the function and display the result.
Create a function that calculates the product of the elements in an array.
Example C++ Exercise
Show C++ Code
#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
}
Output
The product of the array elements is: 120