What is the return value of f(p,p), if the value of p is initialized to 5…
2013
What is the return value of f(p,p), if the value of p is initialized to 5 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;
}
- A.
3024
- B.
6561
- C.
55440
- D.
161051
Attempted by 120 students.
Show answer & explanation
Correct answer: B
Key idea: the first parameter is passed by reference so increments to x persist across recursive calls; the second parameter is a local copy used to stop recursion.
Initial call: x = 5, c = 5
c becomes 4
x becomes 6
call f with x = 6, c = 4
Second call: x = 6, c = 4
c becomes 3
x becomes 7
call f with x = 7, c = 3
Third call: x = 7, c = 3
c becomes 2
x becomes 8
call f with x = 8, c = 2
Fourth call: x = 8, c = 2
c becomes 1
x becomes 9
call f with x = 9, c = 1
Fifth call (base): x = 9, c = 1
c becomes 0 → return 1 (base case)
Backtracking (unwinding recursion): each return multiplies the returned value by the current x (which is 9 for all unwinding steps):
Base returns 1 → first unwind multiplies by 9: 1 × 9 = 9
Next unwind: 9 × 9 = 81
Next: 81 × 9 = 729
Final unwind: 729 × 9 = 6561
Answer: 6561