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?
GATE CSE 2019Algorithms › Program & Function TracingVerified
(D) It will not print anything and will not terminate
Trace the recursion for a positive integer n. The only base case is n < 0, but integer division n / 2 of a nonnegative n stays nonnegative, so n never becomes negative. Once the argument reaches 0, convert(0) keeps calling convert(0), causing infinite recursion. Since every printf is placed after the recursive call, no printf is ever reached.
Since n / 2 for nonnegative n never becomes negative, the base case n < 0 is unreachable; convert(0) recurses forever on convert(0). All printf calls come after the recursive call, so none are ever reached, and the program prints nothing.
Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.