Question

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?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2019 answer key

Solution

Trace the recursive calls to verify if the base condition can ever be met.

The function convert is defined as:

void convert(int n){
    if (n < 0)
        printf("%d", n);
    else {
        convert(n / 2);
        printf("%d", n % 2);
    }
}

Let nn be any positive integer (e.g. n=5n = 5):

  1. Call convert(5): since 5<05 < 0 is false, calls convert(5 / 2) = convert(2).
  2. Call convert(2): since 2<02 < 0 is false, calls convert(2 / 2) = convert(1).
  3. Call convert(1): since 1<01 < 0 is false, calls convert(1 / 2) = convert(0).
  4. Call convert(0): check condition n < 0. For n=0n = 0, 0<00 < 0 is false!
    Therefore, execution proceeds to the else block and calls convert(0 / 2) = convert(0).

Because convert(0) repeatedly calls convert(0), the base condition n < 0 is never reached. This causes an infinite recursion.

Furthermore, all printf statements in the else block are placed after the recursive call convert(n / 2). Because the recursive calls never return, no printf statement is ever executed before the program exhausts the call stack (stack overflow crash).

Hence, it will not print anything and will not terminate (Option D).

Final answer

D

Common trap

Assuming the base case is n <= 0 or n == 0, which would print binary digits.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2019 Computer Science and Information Technology (CS)
Question
36 of 65, printed as CS Q.26
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.