edited by
9,156 views
15 votes
15 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$
edited by

4 Answers

11 votes
11 votes

OUTPUT IS

10101101

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

9 votes
9 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.

0 votes
0 votes

above function is same as 

 

void f (int n) {

        if (n/2) {

        f(n/2);

       }

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

}

and print the same output.

 

Answer : D

Answer:

Related questions

18 votes
18 votes
2 answers
2
26 votes
26 votes
4 answers
3
18 votes
18 votes
3 answers
4