Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

5. Recursion: Consider the following program pubiie elaas Recuraionitystery publ

ID: 3590781 • Letter: 5

Question

5. Recursion: Consider the following program pubiie elaas Recuraionitystery publie static int mystery(int n) ifin0 else ifin-1 else return O return 1 return nmystery(n-2 public static void main (Stringt) args) System.out.println( mystery(1) - System.out.println( mystery(-6)12 System.out.printin( mystery (3) 11- //end of class a) How many base cases are there in the recursive function mystery above? What are they? b) Trace the execution of the function call in statement 3 above? c) What is the output of the above program?

Explanation / Answer

Please find below the simplified answers:

public class RecursionMystery {

public static int mystery(int n)

{

if(n<=0)return 0;

else if (n==1) return 1;

else return n + mystery(n-2);

}

public static void main(String[] args) {

System.out.println(mystery(1));

System.out.println(mystery(-6));

System.out.println(mystery(3));

}

}

a)No of base cases and what are they?

n<=0 is the base cases for return from recursion

if at any point of execution value of n will be zero then it will return 0

n==1 is the another base cases for return from recursion

if at any point of execution value of n will be one then it will return 1

b)Trace the execution of function call

System.out.println(mystery(3));

value of n is 3

first it check n<=0 which is false so it will continue

then it will check n==1 which is also false

then it will go return n + mystery(n-2);

here value of n will be store in stack that is three

and it will call the mystery recusively by subtracting 2 from n

now value of n is 1

so it gonna satisfied the n==1 then it bases cases for return from recursion so value of n will be 1

and it will come down to stack and sum the value of n that was 3 stored in above step

so final value of n will be 3+1 is 4

c)

what is the out put of the program

System.out.println(mystery(1)); //will out put 1

because its satisfies the base condition of recursion that is n==1

System.out.println(mystery(-6));//will out put 0

because its satisfies the base condition of recursion that is n<=0 as -6 is less than 0

System.out.println(mystery(3));// will out put 4

already described in b

//please do let me know if u have any concern...

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote