Sum of all odd length subarrays | Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Given array arr [ ] ; Function call
function OddLengthSum ( arr ) { var sum = 0 ; var l = arr . length ; for ( var i = 0 ; i < l ; i ++ ) { for ( var j = i ; j < l ; j += 2 ) { for ( var k = i ; k <= j ; k ++ ) { sum += arr [ k ] ; } } } return sum ; } var arr = [ 1 , 5 , 3 , 1 , 2 ] document . write ( OddLengthSum ( arr ) ) ;