ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int buf[4], head = 0, count = 0;
for (int v = 1; v <= 6; v++) {
    buf[(head + count) % 4] = v;
    if (count < 4) count++;
    else head = (head + 1) % 4;
}
printf("%d %d", buf[head], buf[(head + count - 1) % 4]);
  1. A. 5 6
  2. B. 3 6
  3. C. 1 4
  4. D. 3 4

Correct answer: B. 3 6

This ring buffer keeps the last 4 values. 1 to 4 fill it; 5 overwrites slot 0 and moves head to 1; 6 overwrites slot 1 and moves head to 2. The buffer is 5 6 3 4, with the oldest value (3) at head and the newest (6) at slot (2 + 3) % 4 = 1.

More C Programming questions

Exams that ask this topic