Program for average of an array without running into overflow | Function to calculate average of an array using standard method ; Stores the sum of array ; Find the sum of the array ; Return the average ; Function to calculate average of an array using efficient method ; Store the average of the array ; Traverse the array arr [ ] ; Update avg ; Return avg ; Input ; Function call
function average ( arr , N ) { var sum = 0 ; for ( var i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum > 2147483647 ) { sum = - 2147483647 + ( sum - 2147483649 ) } return parseInt ( sum / N ) ; } function mean ( arr , N ) { var avg = 0 ; for ( var i = 0 ; i < N ; i ++ ) { avg += parseFloat ( ( arr [ i ] - avg ) / ( i + 1 ) ) ; } return avg ; } var arr = [ 2147483647 , 1 , 2 ] ; var N = arr . length document . write ( " " + average ( arr , N ) . toFixed ( 10 ) + " " ) ; document . write ( " " + mean ( arr , N ) . toFixed ( 10 ) + " " ) ;