ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int walk(int n) {
    static int calls = 0;
    calls++;
    if (n > 1) {
        walk(n / 2);
        walk(n / 3);
    }
    return calls;
}
int main(void) {
    int a = walk(10);
    int b = walk(4);
    printf("%d %d", a, b);
}
  1. A. 9 5
  2. B. 9 14
  3. C. 7 12
  4. D. 9 13

Correct answer: B. 9 14

Let T(n) be the calls made by walk(n): T(0) = T(1) = 1, otherwise 1 + T(n/2) + T(n/3). T(2) = 3, T(3) = 3, T(5) = 1 + T(2) + T(1) = 5, T(10) = 1 + T(5) + T(3) = 9. The counter is static, shared by every call and never reset, and each call returns its current value after its children finish, so a = 9. walk(4) adds T(4) = 1 + T(2) + T(1) = 5 more, so b = 14, not 5.

More C Programming questions

Exams that ask this topic