edited by
8,738 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$
edited by

3 Answers

Best answer
26 votes
26 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.
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
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.
Answer:

Related questions

15 votes
15 votes
4 answers
1
Ishrat Jahan asked Oct 29, 2014
9,150 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); } }What does f(173) print?$010110101$...
18 votes
18 votes
2 answers
2
26 votes
26 votes
4 answers
3
18 votes
18 votes
3 answers
4