Skip to content
Official PYQ · 2019

GATE CS 2019 Q26 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

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 nn as argument?

Choose one option
View worked solution

Answer: D

To understand the behavior of the function, let us trace the execution of convert(n) with a positive integer, say n=5n = 5:

  1. convert(5):
    • Since 5<05 < 0 is false, the else block is executed.
    • It calls convert(5/2), which is convert(2).
  2. convert(2):
    • Since 2<02 < 0 is false, it calls convert(2/2), which is convert(1).
  3. convert(1):
    • Since 1<01 < 0 is false, it calls convert(1/2), which is convert(0).
  4. convert(0):
    • Since 0<00 < 0 is false, it calls convert(0/2), which is convert(0).
  5. convert(0):
    • This again calls convert(0), leading to infinite recursion.

Because the recursive call convert(n/2) is placed before the print statement printf("%d", n%2), the program must wait for the recursive call to complete before it can print anything.

Since the recursion gets stuck in an infinite loop at n=0n = 0 and never terminates, the control never reaches any of the printf statements. Thus, the function will not print anything and will not terminate (practically, it will eventually result in a stack overflow error).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions