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 as argument?
View worked solution
Answer: D
To understand the behavior of the function, let us trace the execution of convert(n) with a positive integer, say :
convert(5):- Since is false, the
elseblock is executed. - It calls
convert(5/2), which isconvert(2).
- Since is false, the
convert(2):- Since is false, it calls
convert(2/2), which isconvert(1).
- Since is false, it calls
convert(1):- Since is false, it calls
convert(1/2), which isconvert(0).
- Since is false, it calls
convert(0):- Since is false, it calls
convert(0/2), which isconvert(0).
- Since is false, it calls
convert(0):- This again calls
convert(0), leading to infinite recursion.
- This again calls
Because the recursive call convert(n/2) is placed before the print statement printf("%d", n%2), the program must wait for the recursive call to complete before it can print anything.
Since the recursion gets stuck in an infinite loop at and never terminates, the control never reaches any of the printf statements. Thus, the function will not print anything and will not terminate (practically, it will eventually result in a stack overflow error).
Free practice · Your answers on this page are not saved.
