A Product Array Puzzle | C ++ program for the above approach ; product of all elements ; counting number of elements which have value 0 ; creating a new array of size n ; if number of elements in array with value 0 is more than 1 than each value in new array will be equal to 0 ; if no element having value 0 than we will insert product / a [ i ] in new array ; if 1 element of array having value 0 than all the elements except that index value , will be equal to 0 ; if ( flag == 1 && a [ i ] == 0 ) ; Driver Code
#include <iostream> NEW_LINE using namespace std ; long * productExceptSelf ( int a [ ] , int n ) { long prod = 1 ; long flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) flag ++ ; else prod *= a [ i ] ; } long * arr = new long [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( flag > 1 ) { arr [ i ] = 0 ; } else if ( flag == 0 ) arr [ i ] = ( prod / a [ i ] ) ; else if ( flag == 1 && a [ i ] != 0 ) { arr [ i ] = 0 ; } else arr [ i ] = prod ; } return arr ; } int main ( ) { int n = 5 ; int array [ ] = { 10 , 3 , 5 , 6 , 2 } ; long * ans ; ans = productExceptSelf ( array , n ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } return 0 ; }