42. Circular Buffer Insert

#include <stdio.h>

typedef struct {
    int buffer[100];
    int head;
    int tail;
    int count;
    int capacity;
} CircularBuffer;

void insert_circular(CircularBuffer *cb, int value) {
    if ((*cb).count == (*cb).capacity) {
        return;  // Buffer full, do not insert
    }

    (*cb).buffer[(*cb).head] = value;                     // Insert value
    (*cb).head = ((*cb).head + 1) % (*cb).capacity;       // Advance head with wrap-around
    (*cb).count++;                                        // Increment element count
}

int main() {
    int n, k;
    scanf("%d %d", &n, &k);

    CircularBuffer cb = { .head = 0, .tail = 0, .count = 0, .capacity = n };

    for (int i = 0; i < k; i++) {
        int val;
        scanf("%d", &val);
        insert_circular(&cb, val);
    }

    for (int i = 0; i < cb.count; i++) {
        printf("%d", cb.buffer[i]);
        if(i < cb.count-1){
           printf(" "); 
        }
    }

    return 0;
}

Alternative solution

void insert_circular(CircularBuffer *cb, int value) {
    if (cb->count == cb->capacity) return;

    cb->buffer[cb->head] = value;
    cb->head = (cb->head + 1) % cb->capacity;
    cb->count++;
}

 

What is a Circular Buffer?

circular buffer (or ring buffer) is a fixed-size data structure that treats the buffer’s start and end as connected in a loop.

Why used in embedded systems?

  • Efficient for UART RX/TX buffering
  • Ideal for DMA data streaming
  • Used in interrupt-safe queues
  • Avoids dynamic memory allocation
     

How the Solution Works:

  1. cb->head points to where the next value should be inserted.
  2. cb->count tracks the number of elements.
  3. Before inserting:
    • Check if buffer is full → if count == capacity, do nothing.
  4. Insert value at buffer[head].
  5. Advance head using: (head + 1) % capacity to wrap around.
  6. Increment count.
     

 

 

Loading...

Input

5 5 10 20 30 40 50

Expected Output

10 20 30 40 50