Consider the code fragment below : #include <stdio.h> void f(int n) { if (n <=…

2008

Consider the code fragment below : 

#include <stdio.h>

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

What does f(173) print?

  1. A.

    010110101

  2. B.

    010101101

  3. C.

    10110101

  4. D.

    10101101

Attempted by 76 students.

Show answer & explanation

Correct answer: D

What the function does: it prints the binary representation of n. The base case prints n when n <= 1. Otherwise it recursively calls f(n/2) and then prints n%2, so outputs the binary digits from most significant to least significant.

Compute successive integer divisions and remainders for 173:

  1. 173 / 2 = 86, remainder 1

  2. 86 / 2 = 43, remainder 0

  3. 43 / 2 = 21, remainder 1

  4. 21 / 2 = 10, remainder 1

  5. 10 / 2 = 5, remainder 0

  6. 5 / 2 = 2, remainder 1

  7. 2 / 2 = 1, remainder 0

  8. 1 is the base case and is printed as 1

When the recursion unwinds the printed digits are (in order): 1 0 1 0 1 1 0 1

Answer: 10101101

Explore the full course: Gate Guidance By Sanchit Sir