ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int n = 10, c = 0;
int k = (n + 3) / 4;
switch (n % 4) {
case 0: do { c++;
case 3: c++;
case 2: c++;
case 1: c++;
} while (--k > 0);
}
printf("%d %d", c, k);- A. 10 0
- B. 12 0
- C. 10 1
- D. 8 0
Correct answer: A. 10 0
This is Duff's device: case labels may sit inside the do-while body. k = 13 / 4 = 3 and n % 4 = 2, so control jumps to case 2 and the first pass does only two increments (c = 2). --k makes k 2 and the loop runs a full pass of four (c = 6), --k = 1 gives another (c = 10), and --k = 0 ends it. c equals n, as intended; 12 assumes three full passes.
More C Programming questions
- What is printed? c int calls = 0; int ways(int n) { calls++; if (n < 0) return 0; if (n == 0) return 1; return ways(n - 1) + ways(n - 3) +…
- What is printed? c int moves = 0; void h(int n, char from, char via, char to) { if (n == 0) return; h(n - 1, from, to, via); if (++moves…
- What is printed? c for (unsigned n = 5; n < 8; n++) printf("%u ", n ^ (n >> 1)); unsigned g = 13, b = 0; for (; g; g >>= 1) b ^= g…
- What is printed? c int walk(int n) { static int calls = 0; calls++; if (n > 1) { walk(n / 2); walk(n / 3); } return calls; } int…
- What is printed? c int calls = 0; int A(int m, int n) { calls++; if (m == 0) return n + 1; if (n == 0) return A(m - 1, 1); return A(m - 1…
- What is printed? c 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…