Question
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?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2019 answer key
Solution
Trace the recursive calls to verify if the base condition can ever be met.
The function convert is defined as:
void convert(int n){
if (n < 0)
printf("%d", n);
else {
convert(n / 2);
printf("%d", n % 2);
}
}
Let be any positive integer (e.g. ):
- Call
convert(5): since is false, callsconvert(5 / 2)=convert(2). - Call
convert(2): since is false, callsconvert(2 / 2)=convert(1). - Call
convert(1): since is false, callsconvert(1 / 2)=convert(0). - Call
convert(0): check conditionn < 0. For , is false!
Therefore, execution proceeds to theelseblock and callsconvert(0 / 2)=convert(0).
Because convert(0) repeatedly calls convert(0), the base condition n < 0 is never reached. This causes an infinite recursion.
Furthermore, all printf statements in the else block are placed after the recursive call convert(n / 2). Because the recursive calls never return, no printf statement is ever executed before the program exhausts the call stack (stack overflow crash).
Hence, it will not print anything and will not terminate (Option D).
D
Assuming the base case is n <= 0 or n == 0, which would print binary digits.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2019 Computer Science and Information Technology (CS)
- Question
- 36 of 65, printed as CS Q.26
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.