Calculate the Product of Array Elements Using a Function in C++

In this exercise, you will learn how to create a function in C++ that calculates the product of all the elements in an array. Multiplying all elements in an array is a common operation in programming, particularly in mathematical and statistical computations.

You will define a function that takes an array and its size as parameters, loops through each element, and multiplies them together to compute the final result. This task will help you practice using loops, function parameters, and array manipulation.

By completing this task, you will reinforce your understanding of array traversal and aggregation logic in C++ programming.

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

 Copy 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

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.