Sum of all subarrays of size K | Java implementation to find the 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
class GFG { static void calcSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += arr [ i ] ; System . out . print ( sum + " ▁ " ) ; for ( int i = k ; i < n ; i ++ ) { sum = ( sum - arr [ i - k ] ) + arr [ i ] ; System . out . print ( sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; int k = 3 ; calcSum ( arr , n , k ) ; } }