in Algorithms edited by
8,773 views
18 votes
18 votes

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$
in Algorithms edited by
8.8k views

1 comment

In Go book ,this questions  are putted in algorithms  ,should  be under recursion  in c programming
0
0

3 Answers

26 votes
26 votes
Best answer
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.
selected by
31 votes
31 votes

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).

edited by

4 Comments

nice approach
0
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 .

correct me please.
1
1
it is if(n/2) not if(n%2)

if(86/2) will be if(43) which is true
0
0
6 votes
6 votes
ans is 3). As P1 prints 10101101 same as given code in question but P2 prints the output in reverse order.
by
Answer:

Related questions