Skip to content
Related Articles

Related Articles

Improve Article

Array product in C++ using STL

  • Last Updated : 19 Apr, 2021

In C++, we can quickly find array product using accumulate() and multiplies<>().
 

The initialProduct specifies the initial value to be considered.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

For multiplication, the initial value is 1.

Eg: array = [5, 10, 15], 



So, Product = 1 x 5 x 10 x 15 = 750  (Notice that 1 is the initial value here)

CPP




// C++ program to find array product
#include <iostream>
#include <numeric>
using namespace std;
 
// User defined function that returns product of
// arr[] using accumulate() library function.
int arrayProduct(int a[], int n)
{
    int initialProduct = 1;
    return accumulate(a, a + n, initialProduct, multiplies<int>());
}
 
int main()
{
    int a[] = { 5, 10, 15 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << arrayProduct(a, n);
    return 0;
}
Output: 
750

 

product of vector 
 

CPP




// C++ program to find vector product
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
 
// User defined function that returns product of
// v using accumulate() library function.
int arrayProduct(vector<int>& v)
{
    int initialProduct = 1;
    return accumulate(v.begin(), v.end(), initialProduct, multiplies<int>());
}
 
int main()
{
    vector<int> v{ 5, 10, 15 };
    cout << arrayProduct(v);
    return 0;
}
Output: 
750

 

We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_product()) for details.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :