Question
2. Part B Problems Video -- 20 min The point of this exercise is to learn how to understand the execution of recursive methods. Please
2. Part B Problems Video -- 20 min
-
The point of this exercise is to learn how to understand the execution of recursive methods. Please watch the video link above, which illustrates a new way to trace a recursive method that is much more effective than the stack diagram approach in the textbook. Then, apply the method shown to the following program, in which we evaluate the call prod(1,4).
| prod(1,4) m=1,n=4 m==n (F) recurse = prod(1,3) m=1,n=3 ... continue! |
-
Type in the definition of the prod method and execute it. Does it perform the way you predicted? Try a couple other calls. Does it behave as expected?
-
We have a triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively the total number of blocks in such a triangle with the given number of rows. For example:
triangleCount(0) 0
triangleCount(1) 1
triangleCount(2) 3
triangleCount(8) 36
public class PartB { public static void main(String [] args) { /************* Prob 5 *********************** // Type in the definition of the prod method where indicated // below main and execute it. // Does it perform the way you predicted?
System.out.println("prod(1,4) = " + prod(1,4)); System.out.println("prod(3,8) = " + prod(3,8)); // Try a couple other calls. // Does it behave as expected?
//************** End Prob 5 ******************/ /************* Prob 6 *********************** // We have a triangle made of blocks. The topmost row // has 1 block, the next row down has 2 blocks, // the next row has 3 blocks, and so on. // // Define the triangleCount method below main to compute // recursively the total number of blocks in such a triangle // with the given number of rows. // Test cases: System.out.println("triangleCount(0) = " + triangleCount(0)); System.out.println("triangleCount(1) = " + triangleCount(1)); System.out.println("triangleCount(2) = " + triangleCount(2)); System.out.println("triangleCount(8) = " + triangleCount(8)); //************** End Prob 6 ******************/ } // type in the prod method here // define the triangleCount method here }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started