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

Recursion and the runtime stack Consider the following recursive method: def mys

ID: 3790936 • Letter: R

Question

Recursion and the runtime stack

Consider the following recursive method:

      def mystery(a, b):

       if a <= b:

           return a

       else:

           return b + mystery(a - 3, b + 1)

Trace the execution of mystery(10, 1). Use indentation to indicate which statements are performed by a given invocation of the method, following the approach used in the lecture notes to trace the sum method.

What is the value returned by mystery(10, 1)?

During the execution of mystery(10, 1), method frames are added and then removed from the stack. How many method frames are on the stack when the base case is reached? You should assume that the initial call to mystery(10, 1) is made from within the main method, and you should include the stack frame for main in your count.

Are there any initial values of the parameters a and b that would produce infinite recursion? Explain briefly.

Explanation / Answer

mystery(10,1)

--> 1+mystery(7,2)           (a>b)

--> 1+2+mystery(4,3)       (a>b)

--> 1+2+3+mystery(1,4)   (a<b)

= 1+2+3+1 = 7

value returned by mystery(10,1) = 7

Number of method Frames needed = 4 (4 calls to mystery())

No,there any no initial values of the parameters a and b that would produce infinite recursion because all the conditions a>b and a<b and a=b are checked and taken care of.

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