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

Write a recursive method that takes two non-negative integers m and n as paramet

ID: 3548990 • Letter: W

Question

Write a recursive method that takes two non-negative integers m and n as parameters and returns the product. The method should not use the built-in multiplication operator: rather, it should perform multiplication through repeated addition.

Here is an example. Say you have to multiply m = 7 by n = 6. Let us perform the recursion on the second argument n. Suppose that we could get someone else to compute m * (n-1), that is, the same problem, but for a smaller value of the second argument. That second person would give us the product of 7 times 5 which is 35. To get the product of 7 times 6, we need to add one more 7: so the answer is 35 + 7 which is 42.

Next, you would ask: what is the base case? The base case would be when n is as small as possible, in this case, 0. For the base case, the product would be 7 times 0 and is 0.

Write the recursive method and test it using the following shell (Fill in the missing code.)

The results of running the program should look like this:

Write a recursive method

that accepts a string str as argument, and prints all the characters in positions 0 through lastPosition in reverse order.

Test your method by adding the method to the program you have already written, commenting out the test harness for the previous method, and inserting a new harness to test this method. Your program will now look like this:

Write a recursive method

that searches for an integer value x in position 0 through lastPosition of an array and return true if the value is found and false otherwise.

Add the method to the program you have already written, comment out the previous test harness, and add with the following code to test your method.

Here is an example of sample input-output session.

Explanation / Answer

find the root and the recursive formula. Here it isn't given to you, but its still pretty easy to figure out. There's actually two roots here: "if k = 1, m * k = m" and "if k = 2, m * k = m + m". Beyond that, the formula is pretty simple: "m * k = m + (m * k-1)". So the recursive method would just call itself for every "k-1":


public int product(int m, int k) {

if (k == 1) {

return m;

} else if (k == 2) {

return (m + m);

} else {

return (product(m, k-1) + m);

}

}


No need to check for >0's, since the problem says you can count on it always being true

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