Sum of all subarrays of size K | C ++ 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
#include <iostream> NEW_LINE using namespace std ; int calcSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += arr [ i ] ; cout << sum << " ▁ " ; for ( int i = k ; i < n ; i ++ ) { sum = ( sum - arr [ i - k ] ) + arr [ i ] ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; calcSum ( arr , n , k ) ; return 0 ; }