How to Find the Product of 2D Array Elements in C++?
Last Updated :
14 Feb, 2024
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++
#include <iostream>
using namespace std;
int main()
{
int rows = 2;
int cols = 2;
int arr[rows][cols] = { { 1, 2 }, { 3, 4 } };
long long product = 1;
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)
Share your thoughts in the comments
Please Login to comment...