Skip to main content

GATE CSE 2019Algorithms › Program & Function TracingVerified

GATE CSE 2019 PYQ: Consider the following C function. void convert ( int n ) { if ( n < 0 ) printf {“% d ”, n ); else { convert…

Consider the following C function.

  1. void convert (int n ) {
  2. if (n<0)
  3. printf{“%d”, n);
  4. else {
  5. convert(n/2);
  6. printf(“%d”, n%2);
  7. }
  8. }

Which one of the following will happen when the function convert is called with any positive integer nn as argument?

  1. A
    It will print the binary representation of nn and terminate
  2. B
    It will print the binary representation of nn in the reverse order and terminate
  3. C
    It will print the binary representation of nn but will not terminate
  4. D
    It will not print anything and will not terminate
    Correct answer

Answer

(D) It will not print anything and will not terminate

Approach

Trace the recursion for a positive integer n. The only base case is n &lt; 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 &lt; 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.