Skip to main content

# 14.11: Exercises

The code for this chapter is in the ch06 directory of ThinkJavaCode. See [Section 0.4] for instructions on how to download the repository. Before you start the exercises, we recommend that you compile and run the examples.

If you have not already read Appendix A.7, now might be a good time. It describes JUnit, a tool for efficiently testing value methods.

Exercise $$\PageIndex{1}$$

If you have a question about whether something is legal, and what happens if it is not, a good way to find out is to ask the compiler. Answer the following questions by trying them out.

1. What happens if you invoke a value method and don’t do anything with the result; that is, if you don’t assign it to a variable or use it as part of a larger expression?
2. What happens if you use a void method as part of an expression? For example, try System.out.println("boo!") + 7;

Exercise $$\PageIndex{2}$$

Write a method named isDivisible that takes two integers, n and m, and that returns true if n is divisible by m, and false otherwise.

Exercise $$\PageIndex{3}$$

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

If any of the three lengths is greater than the sum of the other two, you cannot form a triangle.

Write a method named isTriangle that takes three integers as arguments and returns either true or false, depending on whether you can or cannot form a triangle from sticks with the given lengths. The point of this exercise is to use conditional statements to write a value method

Exercise $$\PageIndex{4}$$

Many computations can be expressed more concisely using the “multadd” operation, which takes three operands and computes a * b + c. Some processors even provide a hardware implementation of this operation for floating-point numbers.

1. Create a new program called Multadd.java.
2. Write a method called multadd that takes three doubles as parameters and that returns a * b + c.
3. Write a main method that tests multadd by invoking it with a few simple parameters, like 1.0, 2.0, 3.0.
4. Also in main, use multadd to compute the following values: \begin{align*} & \sin(\frac{\pi}{4}) + \frac{\cos(\frac{\pi}{4})}{2} \\[5pt] & \log{10} + \log{20} \end{align*}
5. Write a method called expSum that takes a double as a parameter and that uses multadd to calculate: $xe^{-x} + \sqrt{1-e^{-x}} \nonumber$

In the last part of this exercise, you need to write a method that invokes another method you wrote. Whenever you do that, it is a good idea to test the first method carefully before working on the second. Otherwise, you might find yourself debugging two methods at the same time, which can be difficult.

One of the purposes of this exercise is to practice pattern-matching: the ability to recognize a specific problem as an instance of a general category of problems.

Hint

The method for raising e to a power is Math.exp.

Exercise $$\PageIndex{5}$$

What is the output of the following program?

public static void main(String[] args) {
boolean flag1 = isHoopy(202);
boolean flag2 = isFrabjuous(202);
System.out.println(flag1);
System.out.println(flag2);
if (flag1 && flag2) {
System.out.println("ping!");
}
if (flag1 || flag2) {
System.out.println("pong!");
}
}

public static boolean isHoopy(int x) {
boolean hoopyFlag;
if (x % 2 == 0) {
hoopyFlag = true;
} else {
hoopyFlag = false;
}
return hoopyFlag;
}

public static boolean isFrabjuous(int x) {
boolean frabjuousFlag;
if (x > 0) {
frabjuousFlag = true;
} else {
frabjuousFlag = false;
}
return frabjuousFlag;
}

The purpose of this exercise is to make sure you understand logical operators and the flow of execution through value methods.

Exercise $$\PageIndex{6}$$

In this exercise, you will use a stack diagram to understand the execution of the following recursive program.

public static void main(String[] args) {
System.out.println(prod(1, 4));
}

public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n - 1);
int result = n * recurse;
return result;
}
}

1. Draw a stack diagram showing the state of the program just before the last invocation of prod completes.
2. What is the output of this program? (Try to answer this question on paper first, then run the code to check your answer.)
3. Explain in a few words what prod does (without getting into the details of how it works).
4. Rewrite prod without the temporary variables recurse and result. Hint: You only need one line for the else branch.

Exercise $$\PageIndex{7}$$

Write a recursive method named oddSum that takes a positive odd integer n and returns the sum of odd integers from 1 to n. Start with a base case, and use temporary variables to debug your solution. You might find it helpful to print the value of n each time oddSum is invoked.

Exercise $$\PageIndex{8}$$

The goal of this exercise is to translate a recursive definition into a Java method. The Ackermann function is defined for non-negative integers as follows:

$A(m,n) = \begin{cases} n+1 & \mbox{if } m = 0 \\ A(m-1,1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\ A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0 \end{cases} \nonumber$

Write a method called ack that takes two ints as parameters and that computes and returns the value of the Ackermann function.

Test your implementation of Ackermann by invoking it from main and displaying the return value. Note the return value gets very big very quickly. You should try it only for small values of m and n (not bigger than 3).

Write a recursive method called power that takes a double x and an integer n and returns xn.

Hint

A recursive definition of this operation is xn = x · xn−1. Also, remember that anything raised to the zeroth power is 1.

Optional challenge

You can make this method more efficient, when n is even, using xn = ( xn/2 )2.