In C, modify the recursive factorial function so that the computed factorial is stored back through the pointer argument. Which statement should be added where indicated? #include <stdio.h> void fact(int*); int main() { int i = 5; fact(&i); printf("%d ", i); return 0; } void fact(int *j) { static int s = 1; if (*j != 0) { s = s * *j; *j = j - 1; fact(j); / Add a statement here */ } }

Difficulty: Medium

Correct Answer: j = s;

Explanation:


Introduction / Context:
The goal is to complete a recursive factorial function that accumulates the result in a static variable and then stores the final value back through a pointer parameter. You must decide which assignment correctly writes the computed factorial into the caller’s variable after recursion unwinds.


Given Data / Assumptions:

  • j is a pointer to an int supplied by the caller.
  • s is a static accumulator that multiplies descending values until the base case is reached.
  • After the recursive call returns, the factorial has been computed in s.


Concept / Approach:
To write a value back through a pointer parameter, you must assign to the dereferenced pointer, not to the pointer itself. Therefore the correct form is j = s;. Assigning j = s; attempts to store an integer into a pointer variable (type mismatch). Assigning j = &s; tries to put an address into an int lvalue. &j = s; is invalid because you cannot assign to the address-of expression.


Step-by-Step Solution:
Recursive multiplication builds s: for 5 → 54321 = 120.After fact(j) returns, place the result into the caller’s variable: *j = s;.Back in main, printing i shows the factorial value.


Verification / Alternative check:
Test with 5 → expect 120. With 0 → expect 1; ensure the code handles the base case appropriately by placing the final *j = s after the recursion returns.


Why Other Options Are Wrong:
Each alternative is a type or lvalue error, as explained above, and would either not compile or store an invalid representation.


Common Pitfalls:
Forgetting to dereference the pointer when intending to modify the caller’s variable is a frequent mistake in pointer-based APIs.


Final Answer:
*j = s;

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion