Consider the code fragment written in C below: void f(int n) { if (n <= 1) {…
2008
Consider the code fragment written in C below:
void f(int n)
{
if (n <= 1) {
printf("%d", n);
}
else {
f(n / 2);
printf("%d", n % 2);
}
}Which of the following implementations will produce the same output for f(173) as the above code?
P1
void f(int n)
{
if (n / 2) {
f(n / 2);
}
printf("%d", n % 2);
}P2
void f(int n)
{
if (n <= 1) {
printf("%d", n);
}
else {
printf("%d", n % 2);
f(n / 2);
}
}- A.
Both P1 and P2
- B.
P2 only
- C.
P1 only
- D.
Neither P1 nor P2
Attempted by 40 students.
Show answer & explanation
Correct answer: C
Correct answer: P1 only.
Original function: It first calls f(n / 2) and then prints n % 2, so it prints the binary representation from the most significant bit to the least significant bit. For 173, the output is 10101101.
P1: The condition if (n / 2) recurses while n / 2 is nonzero. It still prints n % 2 after the recursive call returns, so the bit order matches the original function.
P2: P2 prints n % 2 before the recursive call. That prints the least significant bits first, giving the reverse order for 173, so it does not match the original output.
Conclusion: Only P1 produces the same output as the original function.