‹ Back to the paper
Question 3
5 marks
Computer ScienceISC 2017 Computer Science Paper 1OutputRecursion
What is the output of the following code?
The following function magicfun() is a part of some class. What will the function magicfun()…
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 magicfun(int n)
{
if (n == 0)
return 0;
else
return magicfun(n / 2) * 10 + (n % 2);
}Answer
Answer
The function returns the binary equivalent of n (written as a decimal number). Verified by running the code: magicfun(7) = 111 and magicfun(10) = 1010.
Dry run for n = 7:
magicfun(7) = magicfun(3)*10 + 7%2 = magicfun(3)*10 + 1
magicfun(3) = magicfun(1)*10 + 3%2 = magicfun(1)*10 + 1
magicfun(1) = magicfun(0)*10 + 1%2 = magicfun(0)*10 + 1
magicfun(0) = 0 (base case)
Unwinding: magicfun(1) = 0*10 + 1 = 1; magicfun(3) = 1*10 + 1 = 11; magicfun(7) = 11*10 + 1 = 111
Return value for n = 7: 111
Dry run for n = 10:
magicfun(10) = magicfun(5)*10 + 10%2 = magicfun(5)*10 + 0
magicfun(5) = magicfun(2)*10 + 5%2 = magicfun(2)*10 + 1
magicfun(2) = magicfun(1)*10 + 2%2 = magicfun(1)*10 + 0
magicfun(1) = magicfun(0)*10 + 1 = 1
Unwinding: magicfun(2) = 1*10 + 0 = 10; magicfun(5) = 10*10 + 1 = 101; magicfun(10) = 101*10 + 0 = 1010
Return value for n = 10: 1010