ProgrammingVery hardProduct company OA
What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value)
What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value)
int f(int n) {
if (n <= 0) return 1;
if (n % 2 == 0) return 2 * f(n - 1);
return 1 + f(n - 1);
}
int main(void) {
printf("%d", f(4));
}- A. 9
- B. 16
- C. 8
- D. 10
Correct answer: D. 10
f(0)=1 (base case). f(1): odd -> 1+f(0) = 1+1 = 2. f(2): even -> 2*f(1) = 2*2 = 4. f(3): odd -> 1+f(2) = 1+4 = 5. f(4): even -> 2*f(3) = 2*5 = 10.
More C Programming questions
- What is printed? (recursion where the base case is reached via an off-by-one condition) c int f(int n) { if (n < 1) return 0; return n +…
- What is printed? (recursion with a pointer parameter used only for read, not accumulation) c int maxOf(int a[], int n) { if (n == 1)…
- What is printed? (recursive function returning a computed value through a chain of ternaries) c int classify(int n) { return n == 0 ? 0…
- 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));