Open In App

How to Find the Product of 2D Array Elements in C++?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, finding the product of all elements in a 2D array means for a given 2D array of order M*N we have to multiply all the elements together. In this article, we will learn how to find the product of elements in a 2D array in C++.

Example

Input:
myArray[2][2] = {{1, 2}, {3, 4}};

Output:
Product of Elements: 24

Multiplying Elements in a 2D Array in C++

To find the product of elements in a 2D array we can simply use loops to iterate through the given 2D array and keep updating the product to product * element at that position. It is important to initialize the product variable to 1 because if we initialize it with 0 then multiplying the elements with 0 results in 0 only.

C++ Program for Multiplying Elements in a 2D Array

The below example demonstrates how we can find a product of elements in a 2D array.

C++




// C++ program to find the product of all elements in a 2D
// array
#include <iostream>
using namespace std;
  
int main()
{
    // creating 2D array
    int rows = 2; // Number of rows
    int cols = 2; // Number of columns
    int arr[rows][cols] = { { 1, 2 }, { 3, 4 } };
  
    // Initialize product to 1
    long long product = 1;
  
    // Iterate over each element in the 2D array
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            product *= arr[i][j];
        }
    }
    cout << "The product of all elements in the array is: "
         << product << endl;
  
    return 0;
}


Output

The product of all elements in the array is: 24

Time Complexity: O(N * M), N and M are number of rows and columns.
Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads