OneBite.Dev - Coding blog in a bite size

Find The Product Of All Elements In An Array In C++

Code snippet for how to Find The Product Of All Elements In An Array In C++ with sample and detail explanation

One of the frequently encountered operations in programming is finding the product of all elements in an array. In this article, we will discuss how to perform this operation using the C++ programming language.

Code Snippet “Product of Array Elements in C++”

Let’s start by sharing a simple yet illustrative code snippet when devising a solution for this problem in C++:

#include<iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int product = 1;

    for(int i = 0; i < n; i++){
        product *= arr[i];
    }

    cout << "The product of all elements in the array is: " << product;
    return 0;
}

Code Explanation for “Product of Array Elements in C++”

The above code snippet works in a rather simple manner. Let’s dive deeper into how each line of the code contributes to finding the product of all elements in an array:

  • #include<iostream>
    using namespace std;

    The program begins by including the iostream standard library and declares that we’re using the ‘std’ namespace.

  • int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    We define an array “arr” with 5 integer elements and further determine the size of the array by dividing the total size of the array by the size of one element. This gives us the total number of elements in the array.

  • int product = 1;

    Initializing the variable “product” with 1 that will be used to hold the cumulative product of all the elements in the array.

  • for(int i = 0; i < n; i++){
        product *= arr[i];
    }

    We then loop through each element in the array using a ‘for’ loop. In the loop, each element of the array is multiplied with the ‘product’ and the result is stored again in ‘product’. This will continue for all the elements in the array.

  • cout << "The product of all elements in the array is: " << product;

    Finally, the ‘product’ variable holds the product of all the elements in the array and is then printed to the console.

With that, the desired output of the product of all array elements is achieved. You can implement this code to different arrays and it will work smoothly.

c-plus-plus