28. Sliding Window Sum

#include <stdio.h>

// Function to calculate sliding window sum
void sliding_window_sum(int arr[], int n, int k) {
    // Loop through each window of size k
    for (int i = 0; i <= n - k; i++) {
        int sum = 0;

        // Calculate sum of current window
        for (int j = i; j < i + k; j++) {
            sum += arr[j];
        }

        printf("%d", sum);
        if(i < n-k){
            printf(" ");
        }
    }
}

int main() {
    int n, k, arr[100];
    scanf("%d %d", &n, &k);

    // Read array elements
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    sliding_window_sum(arr, n, k);
    return 0;
}
  • Outer loop controls the starting index of each window
  • Inner loop accumulates sum from i to i+k-1
  • Total windows = n - k + 1

This pattern is widely used in:

• ADC moving average

• Filtering

• Rolling stats in sensors and data logs

 

Loading...

Input

5 3 1 2 3 4 5

Expected Output

6 9 12