retagged by
16,610 views
23 votes
23 votes

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
retagged by

8 Answers

Best answer
31 votes
31 votes

As per the question, the function convert needs to be called with a positive integer n as argument.

So, when a positive int is passed as argument, function will compute$(n/2)$ which will return the quotient of integer division. 

Again this result of integer division will be passed through compute$(n/2)$ and so on. Each time the no will be divided by $2$ and will gradually become smaller and smaller and close to 0 but it will never be less than 0

Hence, the program will not print anything (as after every function call, the value returned is greater than $0$) and will not terminate. 

PS: Being a C function and hence when run on a computer each recursive call will require creation of activation record consuming memory space. So, eventually the stack memory will run out and program terminates. But such an option is not there. D is the best option here.

Answer (D)

edited by
32 votes
32 votes

I think none of the option matches. 

Ans should be :- "It won't print anything and terminates abruptly".

Remember here infinite looping is not there. It will terminate abruptly because of stackoverflow.

And thus for this question no option matches.

17 votes
17 votes
The print statement will run at the time n value becomes negative or function calls are over.

Divide by 2 won't give a negative result for any positive integer. So theoretically it will not terminate. Also, it won't print anything because printf statement in else part placed after the function call.

It will terminate due to StackOverflow without printing anything.
edited by
2 votes
2 votes
Actually the correct answer for this question must be it terminates by showing error message stackoverflow as there is a limit upto which function calls can be pushed onto the stack and also it doesnot prints anything.And also infinite looping and stackoverflow are two different things so none of the option matches according to the given scenario.
Answer:

Related questions

13 votes
13 votes
4 answers
1
Arjun asked Feb 7, 2019
9,664 views
Consider the following C program :#include<stdio.h int jumble(int x, int y){ x = 2*x+y; return x; } int main(){ int x=2, y=5; y=jumble(y,x); x=jumble(y,x); printf("%d \n"...
12 votes
12 votes
3 answers
4