ProgrammingHardAccenture · Capgemini
What is printed?
What is printed?
typedef int (*Op)(int);
int twice(int x) { return 2 * x; }
int plus3(int x) { return x + 3; }
int apply(Op f, Op g, int x) { return f(g(f(x))); }
int main(void) {
printf("%d %d", apply(twice, plus3, 1), apply(plus3, twice, 1));
}- A. 8 11
- B. 10 11
- C. 11 10
- D. 10 8
Correct answer: B. 10 11
apply runs f, then g, then f again. twice, plus3, twice on 1: 2 → 5 → 10. plus3, twice, plus3 on 1: 4 → 8 → 11. Swapping the roles of f and g changes the result because the operations do not commute.
More C Programming questions
- What is printed? c for (int k = 0; k < 3; k++) { static int s[3]; int a[3] = {0}; s[k] = a[k] = k + 1; printf("%d%d ", s[0] + s[1] + s[2]…
- Assume ASCII. What is printed? c const char s = "pointer"; printf("%c%c%c", s + 1, s[s - 'o' + 2], (s + strlen(s) - 1) - 1);
- With int a = 3, b = 7; which of these statements compile as C (not C++)? c (a > b ? &a : &b) = 0; / (i) / (a > b ? a : b) = 0; / (ii) / a…
- What is printed? c int f(int n) { static int depth = 0; depth++; if (n <= 1) return depth; int a = f(n - 1); int b = f(n - 2); return a +…
- What is printed? c char s[] = "hello world"; char p = strchr(s, 'o'), q = strrchr(s, 'o'); q = '0'; printf("%s %zu %td", s, strlen(p), q…
- What is printed? c unsigned p = 0xB5; p ^= p >> 4; p ^= p >> 2; p ^= p >> 1; printf("%u", p & 1);