Array product in C++ using STL

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
{
    return accumulate(a, a + n, 1, multiplies<int>());
}
  
int main()
{
    int a[] = { 5, 10, 15 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << arrayProduct(a, n);
    return 0;
}

chevron_right


Output:

750

product of vector

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
{
    return accumulate(v.begin(), v.end(), 1, multiplies<int>());
}
  
int main()
{
    vector<int> v{ 5, 10, 15 };
    cout << arrayProduct(v);
    return 0;
}

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.