You are on page 1of 2

Recursion

1. The following function magicfun() is a part of some class. What


will the function magicfun() return, when the value of n=7 and
n=10, respectively? Show the dry run/working:
int  magicfn (int n)  {
 if(n = = 0) 
return 0;
  else 
return magicfn(n/2) * 10 + (n%2);  }
Ans.
7 = > 111 10 =>1010
Binary equivalent of N Working:
Magicfun (7)

return(Magicfun)(3) *10+1)

return(Magicfun(1)*10+1)

return(Magicfun(0)*10+1)

return(0)
Output → 0 * 10 + 1 = 1 1 * 10 + 0 = 11 11 * 10 + 1 = 111
Magicfun (10)

return(Magicfun)(5) *10+0)

return(Magicfun(2)*10+1)

return(Magicfun(1)*10+0)

return(Magicfun(0)*10+1)

return (0) Output → 0 * 10 + 1 = 11 * 10 + 0 = 10
10 * 10 + 1 = 101
101 10 + 0 = 1010
2, The following function Check() is a part of some class. What will the
function Check() return when the values of both ‘m’ and ‘n’ are equal
to 5? Show the dry run/working. [ISC 2016]
int Check (int m, int n) {
if (n == 1)
return – m ––;
else return ++ m + Check (m, ––n);}
Ans.
Output: Check (5, 5) 6 + Check (6, 4) 7 + Check (7, 3) 8 + Check (8, 2) 9 +
Check (9, 1) Hence the output = – 9 + 9 + 8 + 7 + 6 = 21 [ISC Marking
Scheme, 2016]

You might also like