Question:medium

Consider the following ANSI C program.

 

The output of the program upon execution is \(\underline{\hspace{2cm}}\).

Show Hint

Recursive functions with two decreasing parameters often form combinatorial recursion trees.
Updated On: Feb 2, 2026
Show Solution

Correct Answer: 60

Solution and Explanation

To solve the problem, we need to calculate the output of the function foo(int x, int y, int q) when called with the parameters foo(15, 15, 10).

The function implements a recursive structure. Let's break down its logic: 

  • If (x <= 0) && (y <= 0), the function returns q.
  • If x <= 0, it returns foo(x, y-q, q).
  • If y <= 0, it returns foo(x-q, y, q).
  • Otherwise, the function returns foo(x, y-q, q) + foo(x-q, y, q).

Now, let's compute foo(15, 15, 10):

  1. Start with foo(15, 15, 10). Neither condition x <= 0 nor y <= 0 are satisfied, so execute: foo(15, 5, 10) + foo(5, 15, 10).
  2. Calculate foo(15, 5, 10):
    • Reduce to: foo(15, -5, 10) + foo(5, 5, 10).
    • Calculate foo(15, -5, 10): y <= 0, thus foo(5, -5, 10).
    • Calculate foo(5, -5, 10): y <= 0, thus foo(-5, -5, 10).
      • foo(-5, -5, 10): return 10.
    • Calculate foo(5, 5, 10): foo(5, -5, 10) + foo(-5, 5, 10).
    • Already calculated foo(5, -5, 10) = 10.
    • Calculate foo(-5, 5, 10): x <= 0, thus foo(-5, -5, 10).
    • Already calculated foo(-5, -5, 10) = 10.
    • Return 10 + 10 = 20 for foo(5, 5, 10).
    • Return 10 + 20 = 30 for foo(15, 5, 10).
  3. Now calculate foo(5, 15, 10):
    • Reduce to: foo(5, 5, 10) + foo(-5, 15, 10).
    • Already calculated foo(5, 5, 10) = 20.
    • Calculate foo(-5, 15, 10): x <= 0, thus foo(-5, 5, 10).
    • Already calculated foo(-5, 5, 10) = 10.
    • Return 20 + 10 = 30 for foo(5, 15, 10).
  4. Finally, return 30 + 30 = 60 for foo(15, 15, 10).

The output of the program is 60, which falls within the given range of 60, 60.

Was this answer helpful?
0