A Product Array Puzzle | 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 program to test above functions
function productArray ( arr , n ) { if ( n == 1 ) { document . write ( " " ) ; return ; } var i , temp = 1 ; var prod = Array ( n ) . fill ( 0 ) ; for ( j = 0 ; j < n ; j ++ ) prod [ j ] = 1 ; 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 ++ ) document . write ( prod [ i ] + " " ) ; return ; } var arr = [ 10 , 3 , 5 , 6 , 2 ] ; var n = arr . length ; document . write ( " " ) ; productArray ( arr , n ) ;