Consider the code fragment below : #include <stdio.h> void f(int n) { if (n <=…
2008
Consider the code fragment below :
#include <stdio.h>
void f(int n) {
if (n <= 1) {
printf("%d", n);
} else {
f(n / 2);
printf("%d", n % 2);
}
}
What does f(173) print?
- A.
010110101
- B.
010101101
- C.
10110101
- D.
10101101
Attempted by 76 students.
Show answer & explanation
Correct answer: D
What the function does: it prints the binary representation of n. The base case prints n when n <= 1. Otherwise it recursively calls f(n/2) and then prints n%2, so outputs the binary digits from most significant to least significant.
Compute successive integer divisions and remainders for 173:
173 / 2 = 86, remainder 1
86 / 2 = 43, remainder 0
43 / 2 = 21, remainder 1
21 / 2 = 10, remainder 1
10 / 2 = 5, remainder 0
5 / 2 = 2, remainder 1
2 / 2 = 1, remainder 0
1 is the base case and is printed as 1
When the recursion unwinds the printed digits are (in order): 1 0 1 0 1 1 0 1
Answer: 10101101