A Product Array Puzzle | C ++ implementation of above approach ; Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the product array ; Initialize the product array as 1 ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; print the constructed prod array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void productArray ( int arr [ ] , int n ) { if ( n == 1 ) { cout << 0 ; return ; } int i , temp = 1 ; int * prod = new int [ ( sizeof ( int ) * n ) ] ; memset ( prod , 1 , n ) ; for ( i = 0 ; i < n ; i ++ ) { prod [ i ] = temp ; temp *= arr [ i ] ; } temp = 1 ; for ( i = n - 1 ; i >= 0 ; i -- ) { prod [ i ] *= temp ; temp *= arr [ i ] ; } for ( i = 0 ; i < n ; i ++ ) cout << prod [ i ] << " ▁ " ; return ; } int main ( ) { int arr [ ] = { 10 , 3 , 5 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The ▁ product ▁ array ▁ is : ▁ STRNEWLINE " ; productArray ( arr , n ) ; }