The Wayback Machine - https://web.archive.org/web/20211221123316/https://www.geeksforgeeks.org/sum-of-the-product-of-digits-of-all-array-elements/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sum of the Product of digits of all Array elements

  • Last Updated : 21 Dec, 2021

Given an array arr, the task is to find the sum of the product of digits of all array elements

Example:

Hey! Looking for some great resources suitable for young ones? You've come to the right place. Check out our self-paced courses designed for students of grades I-XII. 

Start with topics like Python, HTML, ML, and learn to make some games and apps all with the help of our expertly designed content! So students worry no more, because GeeksforGeeks School is now here!

 



Input: arr[]={11, 23, 41}
Output: 11
Explanation: 1*1 + 2*3 + 4*1 = 1 + 6 + 4 = 1111

Input: arr[]={46, 32, 78, 0}
Output: 86 

Approach: To solve this problem, find the product of digits of all numbers and then just add them up. Follow the below steps to solve this problem:

  1. Create a function findProduct which will get a number and find the product of its digits.
  2. Create a variable sum to store the final answer and initialise it with 0.
  3. Now, traverse the array and for each element:
    • Pass it to the function findProduct and get the product of its digit.
    • Then add its product of digit to sum.
  4. Return sum as the final answer.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the product of the
// digits of a number N
int findProduct(int N)
{
    if (N == 0) {
        return 0;
    }
  
    int product = 1;
    while (N > 0) {
        product *= (N % 10);
        N /= 10;
    }
  
    return product;
}
  
// Function to find the sum of the product of
// digits of all array elements
int sumOfProduct(vector<int> arr)
{
  
    int sum = 0;
    for (auto x : arr) {
        sum += findProduct(x);
    }
  
    return sum;
}
  
// Driver Code
int main()
{
    vector<int> arr = { 46, 32, 78, 0 };
    cout << sumOfProduct(arr);
}
Output:
86

Time Complexity: O(NlogM), where N is the size of the array and M is the maximum number in the array
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!