The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+8 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);

What does f(173) print?

  1. $010110101$
  2. $010101101$
  3. $10110101$
  4. $10101101$
asked in Algorithms by Boss (16.3k points)
edited by | 1.2k views
It can also be solved by drawing a stack and then popping the elements and printing them.

3 Answers

+16 votes
Best answer

Answer: D

The function prints the binary equivalent of the number $n$.

Binary equivalent of $173$ is $10101101$.

answered by Boss (33.8k points)
edited by
+8 votes



i.e Option  D
since recusive funtion calls will be 

1st function call 173/2=86(int part only)

2nd function call 86/2 =43

3rd function call 43/2=21(int part only)

4th function call 21/2=10(int part only)

5th function call 10/2=5

6th function call 5/2=2(integer part only)

7th function call 2/2=1

now in 7th function call condition if(n<=1) will become true 
so  n will be printed( i.e 1 will be printed )

now while returning every function will execute its remaining part of code ie

 printf ("%d", n%2);

So 6th function will print 2 mod 2 =0

5th  function will print 5 mod 2=1

4th function will print 10 mod 2 =0

3rd function will print 21 mod 2 =1

2nd function will print 43 mod 2 =1

1st function will print 86 mod 2 =0

the main f function call will print 173 mod 2 =1

answered by Active (2k points)
+7 votes

Here  before calling f(n/2) we need to push the printf statement into stack.

and we know stack follows LIFO order so Last in First print here.

Hence D is Ans.

answered by Boss (23.4k points)

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,198 answers
71,152 users