Project ForgeSign up free
Programming in C
Programming Fundamentals
GATE 2019
Hard

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?

  • AIt will print the binary representation of n and terminate
  • BIt will print the binary representation of n in the reverse order and terminate
  • CIt will print the binary representation of n but will not terminate
  • It will not print anything and will not terminate

Explanation

For a positive n, repeated integer division n/2 eventually reaches 0 — but 0 is NOT less than 0, so convert(0) takes the else branch and calls convert(0/2)=convert(0) again, forever: infinite recursion, since the base case only catches NEGATIVE n. Since every printf statement is placed AFTER its own recursive call in the code, and that recursive call never returns, NONE of the printf statements ever actually get to execute — nothing is printed, and the program never terminates.

Source: GATE CS 2019 (Set-2) (2019)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free