Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters into the window and subtract the element which pops out from the window of the size K ; Print the sum of subarray ; Drivers Code ; Function Call
function calcSum ( arr , n , k ) { var sum = 0 ; for ( var i = 0 ; i < k ; i ++ ) sum += arr [ i ] ; document . write ( sum + " " ) ; for ( var i = k ; i < n ; i ++ ) { sum = ( sum - arr [ i - k ] ) + arr [ i ] ; document . write ( sum + " " ) ; } } var arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; var n = arr . length ; var k = 3 ; calcSum ( arr , n , k ) ;