Page 425 - Computer science 868 Class 12
P. 425
if(n == 0)
return 0;
else
return magicfun(n/2) * 10 + (n%2);
}
Ans.
magicfun(0) true 0
magicfun(1) false magicfun(0)*10 + 1 0*10 + 1 = 1
magicfun(2) false magicfun(1)*10 + 0 1*10 + 0 = 10
magicfun(5) false magicfun(2)*10 + 1 10*10 + 1 = 101
magicfun(10) false magicfun(5)*10 + 0 101*10 + 1 = 1010
method call Is n==0 return Calculation while popping
n = 10 value returned = 1010
Similarly, when n = 7, the output is 111.
The function is returning the binary equivalent of the number n.
7. The following function magicfun() is a part of some class. What will the function magicfun() return, when the value of n = 125?
Show the dry run/working.
class OutputH
{
String h="";
void magicfun (int n)
{
if(n == 0)
System.out.print(h);
else
{h = ((n%16)>9? (char)((n%16)+55) :(char)((n%16)+48))+h;
magicfun(n/16);
}
}
}
Ans.
magicfun(0) true 7D is printed and stack emptied
magicfun(7) false 7 > 9 false 7D
magicfun(125) false 13 > 9 true D
method call is n = 0 n % 16 > 9 h
Output : 7D
8. The following function Check() is a part of some class. What will the function Check() return when the values of both ‘m’ and
‘n’ is equal to 5? Show the dry run/working.
int Check (int m, int n)
{
if(n = = 1)
return - m --;
else
return + + m + Check (m, -- n);
}
Ans.
Check(9,1) true -9 returned -9
Check(8,2) false 9 + Check(9, 1) - 9 + 9 = 0
Check(7,3) false 8 + Check(8, 2) 0 + 8 = 8
Check(6,4) false 7 + Check(7, 3) 8 + 7 = 15
Check(5,5) false 6 + Check(6, 4) 15 + 6 = 21
method call n == 1 return calculation while popping
423
Recursion 423

