43. Circular Buffer Read

#include <stdio.h>

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

void read_bytes(CircularBuffer *cb, int n) {
    for (int i = 0; i < n; i++) {
        if (cb->count == 0) {
            printf("NULL");
        } else {
            int val = cb->buffer[cb->tail];
            printf("%d", val);
            cb->tail = (cb->tail + 1) % cb->capacity;
            cb->count--;
        }
        if(i < n-1){
            printf(" ");
        }
    }
    printf("\nTail: %d", cb->tail);
}

int main() {
    CircularBuffer cb = {
        .buffer = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
        .head = 3,
        .tail = 7,
        .count = 6,
        .capacity = 10
    };

    int n;
    scanf("%d", &n);

    read_bytes(&cb, n);

    return 0;
}

About Circular Buffers in Firmware

A circular buffer is a fixed-size queue used in embedded firmware to:

  • Store incoming UART/USART bytes
  • Handle ADC sampling results
  • Log interrupt-driven data without dynamic memory

They’re efficient and don’t need memory shifting.

This Problem Demonstrates:

  • Real-world reading logic
  • Underflow handling with "NULL" when count < n
  • Pointer-based state update (tail, count)
     
Loading...

Input

4

Expected Output

80 90 100 10 Tail: 1