1.9k 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$

edited | 1.9k views

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.
by Boss (33.8k points)
selected by

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$

by Veteran (115k points)
edited
+2
+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
0
Can some explain how P1 is giving output?

since if(n/2) condition first check for 173 the 86 which will be false for 86 and 0 will printed first .

ans is 3). As P1 prints 10101101 same as given code in question but P2 prints the output in reverse order.
by Active (1k points)

1
2