ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int a[7] = {1, 2, 3, 4, 5, 6, 7}, n = 7, i = 0;
while (n > 1) {
    i = (i + 2) % n;
    printf("%d ", a[i]);
    for (int j = i; j < n - 1; j++)
        a[j] = a[j + 1];
    n--;
}
printf("| %d", a[0]);
  1. A. 3 6 1 5 2 7 | 4
  2. B. 3 6 2 7 5 4 | 1
  3. C. 2 4 6 1 5 3 | 7
  4. D. 3 6 2 7 5 1 | 4

Correct answer: D. 3 6 2 7 5 1 | 4

This is the Josephus problem with every third person removed. After a removal the later elements shift left, so index i already names the next person and adding 2 skips two people. Removals: index 2 → 3; [1,2,4,5,6,7] index 4 → 6; [1,2,4,5,7] index 1 → 2; [1,4,5,7] index 3 → 7; [1,4,5] index 2 → 5; [1,4] index 0 → 1. Survivor: 4.

More C Programming questions

Exams that ask this topic