Skip to content
Official PYQ · 2013

GATE CS 2013 Q42 — Programming in C

Explain with AI

What is the return value of f(p,p)f(p,p), if the value of pp is initialized to 55 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.
    

int f (int &x, int c) {
       c = c - 1;
       if (c==0) return 1;
       x = x + 1;
       return f(x,c) * x;
}
View worked solution

Answer: 6561

To find the return value of f(p,p)f(p, p) with pp initialized to 55, we analyze the parameter passing mechanisms:

  • The first parameter x is passed by reference, meaning x is an alias for the variable p. Any modification to x directly updates p.
  • The second parameter c is passed by value, meaning c is a local copy of p's value at the time of the call.

Let's trace the execution step-by-step:

  1. Call 1: f(p,5)f(p, 5) where p=5p = 5
    • c becomes 44.
    • x = x + 1 increments pp to 66.
    • Returns f(x, 4) * x.
  2. Call 2: f(p,4)f(p, 4) where p=6p = 6
    • c becomes 33.
    • x = x + 1 increments pp to 77.
    • Returns f(x, 3) * x.
  3. Call 3: f(p,3)f(p, 3) where p=7p = 7
    • c becomes 22.
    • x = x + 1 increments pp to 88.
    • Returns f(x, 2) * x.
  4. Call 4: f(p,2)f(p, 2) where p=8p = 8
    • c becomes 11.
    • x = x + 1 increments pp to 99.
    • Returns f(x, 1) * x.
  5. Call 5: f(p,1)f(p, 1) where p=9p = 9
    • c becomes 00.
    • Since c == 0, it returns 11.

Now, we unwind the recursion. Since x is a reference to p, and the value of p is 99 at the end of the recursion, any evaluation of x during the multiplication phase will use the current value of pp, which is 99:

  • Call 4 returns: 1×9=91 \times 9 = 9
  • Call 3 returns: 9×9=819 \times 9 = 81
  • Call 2 returns: 81×9=72981 \times 9 = 729
  • Call 1 returns: 729×9=6561729 \times 9 = 6561

Thus, the final return value is 6561.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions