ProgrammingVery hardProduct company OA
What is printed? Assume no stack overflow for this depth.
What is printed? Assume no stack overflow for this depth.
int f(int n) {
if (n == 0) return 0;
if (n % 3 == 0) return 1 + f(n - 3);
return f(n - 1);
}
int main(void) { printf("%d", f(10)); }- A. 2
- B. 3
- C. 4
- D. 10
Correct answer: B. 3
f(10)->f(9) [not mult of 3 skip via n%3==0 check fails for 10, so f(9)]. f(9): 9%3==0, 1+f(6). f(6): 1+f(3). f(3): 1+f(0). f(0)=0. So f(3)=1, f(6)=2, f(9)=3, f(10)=f(9)=3 (10 isn't divisible by 3, it just passes through to f(9) with no +1).
More C Programming questions
- What is printed? c int f(int n) { if (n == 0) return 0; int r = f(n - 1); printf("%d ", n); return r; } int main(void) { int x = f(4)…
- What is printed? c union U { char c; int i; double d; }; printf("%zu", sizeof(union U));
- Assume a 64-bit LP64 ABI. What is printed? c struct Inner { char c; int i; }; struct Outer { int x; struct Inner in; double d; }…
- On a typical x86-64 GCC/Clang target, what is printed? c struct F { unsigned a : 20; unsigned b : 20; }; printf("%zu", sizeof(struct F));
- Assume a 64-bit LP64 ABI. What is printed? c struct S { char c; int arr[2]; }; printf("%zu %zu", sizeof(struct S), offsetof(struct S, arr));
- Assume a 64-bit LP64 ABI. What is printed? c struct Node { int val; struct Node next; }; printf("%zu", sizeof(struct Node));