ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int calls = 0;
int A(int m, int n) {
    calls++;
    if (m == 0) return n + 1;
    if (n == 0) return A(m - 1, 1);
    return A(m - 1, A(m, n - 1));
}
int main(void) {
    int r = A(2, 2);
    printf("%d %d", r, calls);
}
  1. A. 7 27
  2. B. 5 14
  3. C. 7 19
  4. D. 6 27

Correct answer: A. 7 27

This is the Ackermann function, with A(1, n) = n + 2 and A(2, n) = 2n + 3, so A(2, 2) = 7. Counting calls: A(1, n) takes 2n + 2 calls, A(2, 0) = A(1, 1) takes 1 + 4 = 5, A(2, 1) = A(1, A(2, 0)) = A(1, 3) takes 1 + 5 + 8 = 14, and A(2, 2) = A(1, A(2, 1)) = A(1, 5) takes 1 + 14 + 12 = 27 calls. 5 and 14 are the value and call count of A(2, 1).

More C Programming questions

Exams that ask this topic