The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+13 votes
1.7k views

Consider the code fragment written in C below :
        

void f (int n)
{ 
    if (n <= 1)  {
        printf ("%d", n);
    }
    else {
        f (n/2);
        printf ("%d", n%2);
    }
}

Which of the following implementations will produce the same output for $f(173)$ as the above code?

P1 P2
void f (int n)
{ 
    if (n/2)  {
        f(n/2);
    }
    printf ("%d", n%2);
}
void f (int n)
{ 
    if (n <=1)  {
        printf ("%d", n);
    }
    else {
        printf ("%d", n%2);
        f (n/2);
    }
}
  1. Both $P1$ and $P2$
  2. $P2$ only
  3. $P1$ only
  4. Neither $P1$ nor $P2$
asked in Algorithms by Boss (16.3k points)
edited by | 1.7k views

4 Answers

+22 votes
Best answer

 

Here, $P1$ and $P2$ will print opposite in direction as shown in diagram.

And given code fragment will print like $P1$ and not like $P2$

Hence, answer will be (C).

answered by Veteran (112k points)
edited by
+2
nice answer.
+1
tnks :)
+1
P1 is printing a leading 0,so shouldn't it be option (D) ?
0

There is no leading 0 printed. On reaching f(1) in P1, there's a check if(n/2){..}. The check fails and does not result in 0 being printed since f(0) is not invoked.

+1
once we know what the code is doing take smaller inputs on which output is  not a palindrome so that you are able to make a difference which function is doing what

like binary of 6 is 110(This binary output is not a palindrome), but P2 prints 011, so it is wrong.
0
nice approach
+13 votes
Answer: C

The code fragment written in C and P1 prints the binary equivalent of the number n.

P2 prints the binary equivalent of the number n in reverse.
answered by Boss (33.8k points)
+6 votes
ans is 3). As P1 prints 10101101 same as given code in question but P2 prints the output in reverse order.
answered by Active (1k points)
0 votes
I think the answer is D, because with P1 code we will always print a leading 0 in the answer but with the given code leading zero is not possible.
eg. n=3
given code will print 11
P1 will print 011.
So, the answers are different.
The answer is D.
answered by (373 points)
Answer:

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,588 questions
54,197 answers
187,535 comments
71,152 users