ProgrammingHardIBM · Deloitte pattern
What is printed? (recursive function returning a computed value through a chain of ternaries)
What is printed? (recursive function returning a computed value through a chain of ternaries)
int classify(int n) {
return n == 0 ? 0 : (n % 2 == 0 ? 1 + classify(n - 2) : 1 + classify(n - 1));
}
int main(void) {
printf("%d", classify(7));
}- A. 7
- B. 6
- C. 4
- D. 3
Correct answer: C. 4
Each call peels off either 1 (odd n, step to n-1) or 2 (even n, step to n-2), adding exactly 1 to the result either way: 7->6->4->2->0 is 4 steps, so classify(7) = 4.
More C Programming questions
- What is printed? c #define SQUARE(x) x x int main(void) { int a = 3; printf("%d", SQUARE(a + 1)); }
- What is printed? c #define PRINT(x) printf(#x " = %dn", x) int main(void) { int apple = 10; PRINT(apple); }
- What is printed? c #define CONCAT(a, b) a ## b int xy = 100; printf("%d", CONCAT(x, y));
- What is printed? c #define N 5 #undef N #define N 10 printf("%d", N);
- What is printed? c #if defined(DEBUG) #define LOG(msg) printf("DEBUG: %sn", msg) #else #define LOG(msg) #endif int main(void) {…
- What is printed? c #define VERSION 2 #if VERSION >= 2 const char msg = "new"; #else const char msg = "old"; #endif int main(void) {…