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]);- A. 3 6 1 5 2 7 | 4
- B. 3 6 2 7 5 4 | 1
- C. 2 4 6 1 5 3 | 7
- 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
- What is printed? c / LP64: 4-byte int, 8-byte pointers / void f(int m[][4], int n) { printf("%zu %zu %td ", sizeof m, sizeof m[0], (char…
- What is printed? c int a = 1, b = 2, c = 3; a += b -= c = 2; int d = (a, b) > c ? a-- : c++; printf("%d %d %d %d", a, b, c, d);
- What is printed? c int a[] = {1, 2, 3, 4, 5}; int p = a + 1, q = &a[4]; printf("%td %d %d", q - p, p + q, p[2]);
- With 4-byte int, what is printed? c int a[3][4] = {0}; int (p)[4] = a; int q = &a[0][0]; printf("%td %td %td", (p + 2) - p, (char )(p + 1)…
- What is printed? c int calls = 0; int f(int n) { calls++; return n < 2 ? n : f(n / 2) + f(n - 1); } int main(void) { int r = f(6)…
- Assume 32-bit unsigned int. What is printed? c unsigned x = 0xB8; / 1011 1000 / printf("%u %u %u", x & (x - 1), x | (x - 1), x & -x);