The GATE Grind

GATE 2019 CS – Question 36

Programming and Data Structures · Recursion · 2 marks · Multiple choice

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?

  1. It will print the binary representation of n and terminate
  2. It will print the binary representation of n in the reverse order and terminate
  3. It will print the binary representation of n but will not terminate
  4. It will not print anything and will not terminate

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) It will not print anything and will not terminate

Explanation

For $n\ge0$ the function calls itself with $n/2$, which tends to 0 but never becomes negative. So the recursion never reaches the base case $n<0$, never prints anything and does not terminate (it ends in a stack overflow).