ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int walk(int n) {
static int calls = 0;
calls++;
if (n > 1) {
walk(n / 2);
walk(n / 3);
}
return calls;
}
int main(void) {
int a = walk(10);
int b = walk(4);
printf("%d %d", a, b);
}- A. 9 5
- B. 9 14
- C. 7 12
- D. 9 13
Correct answer: B. 9 14
Let T(n) be the calls made by walk(n): T(0) = T(1) = 1, otherwise 1 + T(n/2) + T(n/3). T(2) = 3, T(3) = 3, T(5) = 1 + T(2) + T(1) = 5, T(10) = 1 + T(5) + T(3) = 9. The counter is static, shared by every call and never reset, and each call returns its current value after its children finish, so a = 9. walk(4) adds T(4) = 1 + T(2) + T(1) = 5 more, so b = 14, not 5.
More C Programming questions
- 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…
- 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)…