Java Reference
In-Depth Information
We then need a loop that will generate the other values. The user will input a param-
eter telling us how many times to go through the loop, but we don't want to execute the
loop body
length
times: Remember that the starting value is part of the sequence, so if
we want to use a sequence of the given length, we have to make sure that the number of
iterations is one less than
length
. Combining this idea with the
max
/
min
pseudocode,
we know the loop will look like this:
for (int i = 1; i <= length - 1; i++) {
compute next number.
if (value > max) {
max = value.
} else if (value < min) {
min = value.
}
}
print max and min.
To fill out the pseudocode for “compute next number,” we need to translate the
hailstone formula into code. The formula is different, depending on whether the cur-
rent value is odd or even. We can use an
if/else
statement to solve this task. For the
test, we can use a “mod 2” test to see what remainder we get when we divide by 2.
Even numbers have a remainder of 0 and odd numbers have a remainder of 1. So the
test should look like this:
if (value % 2 == 0) {
do even computation.
} else {
do odd computation.
}
Translating the hailstone mathematical formulas into Java, we get the following code:
if (value % 2 == 0) {
value = value / 2;
} else {
value = 3 * value + 1;
}
The only part of our pseudocode that we haven't filled in yet is the part that prints
the result. This part comes after the loop and is fairly easy to complete. Here is the
complete method:
public static void printHailstoneMaxMin(int value, int length) {
int min = value;
int max = value;
Search WWH ::
Custom Search