Consider the following C function. void convert(int n){ if(n<0)…
2019
Consider the following C function.
void convert(int n){
if(n<0)
printf(“%d”,n);
else {
convert(n/2);
printf(“%d”,n%2);
}
}
Which one of the following will happen when the function convert is called with any positive integer n as argument?
- A.
It will print the binary representation of n and terminate
- B.
It will print the binary representation of n in the reverse order and terminate
- C.
It will print the binary representation of n but will not terminate
- D.
It will not print anything and will not terminate
Attempted by 224 students.
Show answer & explanation
Correct answer: D
Key insight: The function recurses on n/2 before printing n%2, which would print binary digits from most significant to least significant if there were an appropriate base case. However, the base condition is incorrect for nonnegative inputs.
For positive n the recursion sequence is n, n/2, n/4, ... and eventually reaches 0.
The base case checks for n < 0. When n becomes 0, 0 < 0 is false, so the function calls convert(0) again.
Therefore convert(0) calls convert(0) repeatedly, causing infinite recursion. The execution never reaches the printf calls placed after the recursive call.
Conclusion: When called with any positive integer, the function will not print anything and will not terminate (infinite recursion).
Note: To correctly print the binary representation and terminate, use a base case that stops at n==0 (handling n==0 separately) or at n<=1, and ensure negative values are handled appropriately.
A video solution is available for this question — log in and enroll to watch it.