In: Computer Science
Consider the following recursive method in Java
public static int mystery(int n)
{
if (n == 0)
return 1;
else
return 4 * mystery (n - 1);
}
What is the output of mystery (3) using the code segment above
Show your work on your trace file
Step1
mystery (3) 3 is passed to mystery() method
public static int mystery(int n) n store the value 3 n = 3
{
if (n == 0) n value is not 0, False execute else part
return 1;
else
return 4 * mystery (n - 1); 4 * mystery(3-1) ===> 4 * mystery(2), again calling mystery() method, passing 2
}
Step2
public static int mystery(int n) n store the value 2, n = 2
{
if (n == 0) n value is not 0, False execute else part
return 1;
else
return 4 * mystery (n - 1); 4 * mystery(2-1) ===> 4 * mystery(1), again calling mystery() method, passing 1
}
Step3
public static int mystery(int n) n store the value 1, n = 1
{
if (n == 0) n value is not 0, False execute else part
return 1;
else
return 4 * mystery (n - 1); 4 * mystery(1-1) ===> 4 * mystery(0), again calling mystery() method, passing 0
}
Step4
public static int mystery(int n) n store the value 0, n = 0
{
if (n == 0) n value is 0, True execute if block part
return 1; return 1 to step3 mystery(0)
else
}
4 * mystery(0);
= 4 * 1
4 return to step2 mystery(1)
4 * mystery(1)
= 4 * 4
16 return to step1 mystery(2)
4 * mystery(2)
4 * 16
= 64
NOTE: If you have any doubt, please let me know through comments; I will surely revert back to you.
Please give a up vote .....
Thank you...