ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int inc(int x) { return x + 1; }
int dbl(int x) { return x * 2; }
int sqr(int x) { return x * x; }
int apply(int (*f[])(int), int n, int x) {
return n == 0 ? x : f[n - 1](apply(f, n - 1, x));
}
int main(void) {
int (*t[])(int) = {inc, dbl, sqr, inc};
printf("%d %d", apply(t, 4, 2), apply(t + 1, 2, 3));
}- A. 19 36
- B. 37 18
- C. 37 36
- D. 37 64
Correct answer: C. 37 36
The recursion applies f[0] innermost and f[n − 1] outermost, i.e. the table is applied left to right: inc(2) = 3, dbl → 6, sqr → 36, inc → 37. A function-pointer array parameter is just a pointer, so t + 1 is a table starting at dbl; with n = 2 it computes sqr(dbl(3)) = 36. '19' applies the table right to left (inc, sqr, dbl, inc); '18' does dbl(sqr(3)).
More C Programming questions
- What is printed? c int s = 0; for (int i = 0; i < 6; i++) { switch (i % 4) { case 0: s += 1; case 1: s += 2; break; case 2: continue…
- What is printed? c int calls; int f(int n) { calls++; return n < 3 ? n : f(n - 1) + f(n - 3); } int main(void) { int r = f(8); printf("%d…
- What is printed? c char s[] = "aaabccdddd"; char r = s, w = s; while (r) { char c = r; int n = 0; while (r == c) { r++; n++; } w++ = c; if…
- Assume 32-bit unsigned int. What is printed? c unsigned int x = 0x5Cu; / 0101 1100 / unsigned int low = x & -x; unsigned int y = x + low…
- Assume 4-byte int with 4-byte alignment. What is printed? c struct P { char tag; int v; }; struct P a[4] = {{'a', 1}, {'b', 2}, {'c', 3}…
- Assume plain char is signed 8-bit, two's complement, and EOF is −1. What is printed? c char c = 'xff'; printf("%d %d %d %d", c == 0xFF…