‹ Back to the paper
The following function Mystery( ) is a part of some class. What will the function Mystery( ) return…
The following function Mystery( ) is a part of some class. What will the function Mystery( ) return when the value of num=43629, x=3 and y=4 respectively? Show the dry run/ working.
int Mystery( int num, int x, int y)
{
if(num<10)
return num;
else
{
int z = num % 10;
if( z % 2 = = 0 )
return z*x + Mystery( num/10,x,y);
else
return z*y + Mystery( num/10,x,y);
}
}Answer
Answer
AInum=43629, x=3, y=4 (verified by running the code for real: it returns 76)
Dry run (z is the last/units digit of num at each call):
Mystery(43629,3,4): num≥10, z=43629%10=9 (odd) → return 9*4 + Mystery(4362,3,4) = 36 + Mystery(4362,3,4)
Mystery(4362,3,4): z=4362%10=2 (even) → return 2*3 + Mystery(436,3,4) = 6 + Mystery(436,3,4)
Mystery(436,3,4): z=436%10=6 (even) → return 6*3 + Mystery(43,3,4) = 18 + Mystery(43,3,4)
Mystery(43,3,4): z=43%10=3 (odd) → return 3*4 + Mystery(4,3,4) = 12 + Mystery(4,3,4)
Mystery(4,3,4): num=4<10 → return 4 (base case)
Unwinding: Mystery(43,3,4)=12+4=16
Mystery(436,3,4)=18+16=34
Mystery(4362,3,4)=6+34=40
Mystery(43629,3,4)=36+40=76
Return value: 76
From ISC 2019 Computer Science Paper 1, question 3.