Open In App

How to Find the Cumulative Product of Elements in an Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is a data structure that stores elements of the same type in contiguous memory locations. The cumulative product of an array is the result of multiplying all the elements in the array. In this article, we will learn how to find the cumulative product of elements in an array in C++.

Example:

Input: 
myArray = {1, 2, 3, 4, 5}

Output:
Cumulative Product: 120

Cumulative Product of an Array in C++

To find the cumulative product of the elements in an array, we can use a simple for loop to iterate through the array and multiply each element with the product of the previous elements. Keep in mind the type of data you are using to store the product so that it doesn’t overflow. You can take a long long to be on the safe side.

C++ Program to Find the Cumulative Product of an Array

The below example demonstrates the use of a for loop to find the cumulative product of a given array in C++.

C++
// C++ Program to illustrate how to find the cumulative
// product of elements in an array
#include <iostream>
using namespace std;

int main()
{
    // initializing array
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // variable to store the cumulative product
    int product = 1;

    // using a for loop to find the cumulative product of
    // the elements in the array.
    for (int i = 0; i < n; i++) {
        product *= arr[i];
    }

    cout << "The cumulative product of the array is: "
         << product << endl;

    return 0;
}

Output
The cumulative product of the array is: 120

Time Complexity: O(N), here N is the number of elements in the array.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads