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?

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? Correct Answer It will not print anything and will not terminate

Let us consider n = 1

Since n > 0 else part gets executed

convert(1/2) = convert(0) // integer division in C

Now, n = 0

But base condition is n < 0 again else part gets executed

convert(0/2) = convert(0) // recursive calls until stack memory gets exhausted

This code will never satisfy base condition and will not terminate until stack memory gets exhausted

Since this option is not available choose the best possible option

Option d → “It will not print anything and will not terminate”

It is partially correct since it will not print anything but also gets terminated

Note:
Answer key in GATE 2019: D

Related Questions

Determine output:
#include void main(){ char *p = NULL; char *q = 0; if(p) printf(" p "); else printf("nullp"); if(q) printf("q"); else printf(" nullq");}