0% found this document useful (0 votes)
44 views2 pages

Recursion Document

The function magicfun() recursively calculates the binary representation of the input number n. When called with inputs 7 and 10, it returns 111 and 1010 respectively by recursively dividing n by 2 and adding the remainders. The function Check() recursively calls itself, decrementing n each time and incrementing/decrementing m. When called with both inputs equal to 5, it returns 21 by recursively processing the inputs in the described manner.

Uploaded by

Andrina Praveen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views2 pages

Recursion Document

The function magicfun() recursively calculates the binary representation of the input number n. When called with inputs 7 and 10, it returns 111 and 1010 respectively by recursively dividing n by 2 and adding the remainders. The function Check() recursively calls itself, decrementing n each time and incrementing/decrementing m. When called with both inputs equal to 5, it returns 21 by recursively processing the inputs in the described manner.

Uploaded by

Andrina Praveen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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